fixed bug related to Codesonar 10818.81116
[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 3, 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_common.h"
29 #include "gnunet_constants.h"
30 #include "gnunet_protocols.h"
31 #include "gnunet_connection_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 #if BUILD_HTTPS
44 #define LIBGNUNET_PLUGIN_TRANSPORT_INIT libgnunet_plugin_transport_https_init
45 #define LIBGNUNET_PLUGIN_TRANSPORT_DONE libgnunet_plugin_transport_https_done
46 #define LIBGNUNET_PLUGIN_TRANSPORT_COMPONENT transport_https
47 #define PROTOCOL_PREFIX "https"
48 #else
49 #define LIBGNUNET_PLUGIN_TRANSPORT_INIT libgnunet_plugin_transport_http_init
50 #define LIBGNUNET_PLUGIN_TRANSPORT_DONE libgnunet_plugin_transport_http_done
51 #define LIBGNUNET_PLUGIN_TRANSPORT_COMPONENT transport_http
52 #define PROTOCOL_PREFIX "http"
53 #endif
54
55 #define DEBUG_HTTP GNUNET_NO
56 #define DEBUG_CURL GNUNET_NO
57 #define DEBUG_MHD GNUNET_NO
58 #define DEBUG_CONNECTIONS GNUNET_NO
59 #define DEBUG_SESSION_SELECTION GNUNET_NO
60 #define DEBUG_SCHEDULING GNUNET_NO
61 #define CURL_TCP_NODELAY GNUNET_YES
62
63 #define INBOUND GNUNET_NO
64 #define OUTBOUND GNUNET_YES
65
66
67
68 /**
69  * Text of the response sent back after the last bytes of a PUT
70  * request have been received (just to formally obey the HTTP
71  * protocol).
72  */
73 #define HTTP_PUT_RESPONSE "Thank you!"
74
75 /**
76  * After how long do we expire an address that we
77  * learned from another peer if it is not reconfirmed
78  * by anyone?
79  */
80 #define LEARNED_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 6)
81
82 /**
83  * Page returned if request invalid
84  */
85 #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>"
86
87 /**
88  * Timeout for a http connect
89  */
90 #define HTTP_CONNECT_TIMEOUT 30
91
92
93 /**
94  * Network format for IPv4 addresses.
95  */
96 struct IPv4HttpAddress
97 {
98   /**
99    * Linked list next
100    */
101   struct IPv4HttpAddress * next;
102
103   /**
104    * Linked list previous
105    */
106   struct IPv4HttpAddress * prev;
107
108   /**
109    * IPv4 address, in network byte order.
110    */
111   uint32_t ipv4_addr GNUNET_PACKED;
112
113   /**
114    * Port number, in network byte order.
115    */
116   uint16_t u_port GNUNET_PACKED;
117
118 };
119
120
121 /**
122  * Network format for IPv6 addresses.
123  */
124 struct IPv6HttpAddress
125 {
126   /**
127    * Linked list next
128    */
129   struct IPv6HttpAddress * next;
130
131   /**
132    * Linked list previous
133    */
134   struct IPv6HttpAddress * prev;
135
136   /**
137    * IPv6 address.
138    */
139   struct in6_addr ipv6_addr GNUNET_PACKED;
140
141   /**
142    * Port number, in network byte order.
143    */
144   uint16_t u6_port GNUNET_PACKED;
145
146 };
147
148
149 /**
150  *  Message to send using http
151  */
152 struct HTTP_Message
153 {
154   /**
155    * next pointer for double linked list
156    */
157   struct HTTP_Message * next;
158
159   /**
160    * previous pointer for double linked list
161    */
162   struct HTTP_Message * prev;
163
164   /**
165    * buffer containing data to send
166    */
167   char *buf;
168
169   /**
170    * amount of data already sent
171    */
172   size_t pos;
173
174   /**
175    * buffer length
176    */
177   size_t size;
178
179   /**
180    * Continuation function to call once the transmission buffer
181    * has again space available.  NULL if there is no
182    * continuation to call.
183    */
184   GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
185
186   /**
187    * Closure for transmit_cont.
188    */
189   void *transmit_cont_cls;
190 };
191
192
193 struct HTTP_PeerContext
194 {
195   /**
196    * peer's identity
197    */
198   struct GNUNET_PeerIdentity identity;
199
200   /**
201    * Pointer to the global plugin struct.
202    */
203   struct Plugin *plugin;
204
205   /**
206    * Linked list of connections with this peer
207    * head
208    */
209   struct Session * head;
210
211   /**
212    * Linked list of connections with this peer
213    * tail
214    */
215   struct Session * tail;
216
217   /**
218    * id for next session
219    */
220   size_t session_id_counter;
221
222   /**
223    * Last session used to send data
224    */
225   struct Session * last_session;
226
227   /**
228    * The task resetting inbound quota delay
229    */
230   GNUNET_SCHEDULER_TaskIdentifier reset_task;
231
232   /**
233    * Delay from transport service inbound quota tracker when to receive data again
234    */
235   struct GNUNET_TIME_Relative delay;
236 };
237
238
239 struct Session
240 {
241   /**
242    * API requirement.
243    */
244   struct SessionHeader header;
245
246   /**
247    * next session in linked list
248    */
249   struct Session * next;
250
251   /**
252    * previous session in linked list
253    */
254   struct Session * prev;
255
256   /**
257    * address of this session
258    */
259   void * addr;
260
261   /**
262    * address length
263    */
264   size_t addrlen;
265
266   /**
267    * target url
268    */
269   char * url;
270
271   /**
272    * Message queue for outbound messages
273    * head of queue
274    */
275   struct HTTP_Message * pending_msgs_head;
276
277   /**
278    * Message queue for outbound messages
279    * tail of queue
280    */
281   struct HTTP_Message * pending_msgs_tail;
282
283   /**
284    * partner peer this connection belongs to
285    */
286   struct HTTP_PeerContext * peercontext;
287
288   /**
289    * message stream tokenizer for incoming data
290    */
291   struct GNUNET_SERVER_MessageStreamTokenizer *msgtok;
292
293   /**
294    * session direction
295    * outbound: OUTBOUND (GNUNET_YES)
296    * inbound : INBOUND (GNUNET_NO)
297    */
298   unsigned int direction;
299
300   /**
301    * is session connected to send data?
302    */
303   unsigned int send_connected;
304
305   /**
306    * is send connection active?
307    */
308   unsigned int send_active;
309
310   /**
311    * connection disconnect forced (e.g. from transport)
312    */
313   unsigned int send_force_disconnect;
314
315   /**
316    * is session connected to receive data?
317    */
318   unsigned int recv_connected;
319
320   /**
321    * is receive connection active?
322    */
323   unsigned int recv_active;
324
325   /**
326    * connection disconnect forced (e.g. from transport)
327    */
328   unsigned int recv_force_disconnect;
329
330   /**
331    * id for next session
332    * NOTE: 0 is not an ID, zero is not defined. A correct ID is always > 0
333    */
334   size_t session_id;
335
336   /**
337    * entity managing sending data
338    * outbound session: CURL *
339    * inbound session: mhd_connection *
340    */
341   void * send_endpoint;
342
343   /**
344    * entity managing recieving data
345    * outbound session: CURL *
346    * inbound session: mhd_connection *
347    */
348   void * recv_endpoint;
349
350   /**
351    * Current queue size
352    */
353   size_t queue_length_cur;
354
355   /**
356         * Max queue size
357         */
358   size_t queue_length_max;
359
360 };
361
362 /**
363  * Encapsulation of all of the state of the plugin.
364  */
365 struct Plugin
366 {
367   /**
368    * Our environment.
369    */
370   struct GNUNET_TRANSPORT_PluginEnvironment *env;
371
372   /**
373    * Handle for reporting statistics.
374    */
375   struct GNUNET_STATISTICS_Handle *stats;
376
377   /**
378    * Plugin Port
379    */
380   uint16_t port_inbound;
381
382   struct GNUNET_CONTAINER_MultiHashMap *peers;
383
384   /**
385    * Daemon for listening for new IPv4 connections.
386    */
387   struct MHD_Daemon *http_server_daemon_v4;
388
389   /**
390    * Daemon for listening for new IPv6connections.
391    */
392   struct MHD_Daemon *http_server_daemon_v6;
393
394   /**
395    * Our primary task for http daemon handling IPv4 connections
396    */
397   GNUNET_SCHEDULER_TaskIdentifier http_server_task_v4;
398
399   /**
400    * Our primary task for http daemon handling IPv6 connections
401    */
402   GNUNET_SCHEDULER_TaskIdentifier http_server_task_v6;
403
404   /**
405    * The task sending data
406    */
407   GNUNET_SCHEDULER_TaskIdentifier http_curl_task;
408
409   /**
410    * cURL Multihandle
411    */
412   CURLM * multi_handle;
413
414   /**
415    * ipv4 DLL head
416    */
417   struct IPv4HttpAddress * ipv4_addr_head;
418
419   /**
420    * ipv4 DLL tail
421    */
422   struct IPv4HttpAddress * ipv4_addr_tail;
423
424   /**
425    * ipv6 DLL head
426    */
427   struct IPv6HttpAddress * ipv6_addr_head;
428
429   /**
430    * ipv6 DLL tail
431    */
432   struct IPv6HttpAddress * ipv6_addr_tail;
433
434   /**
435    * Our ASCII encoded, hashed peer identity
436    * This string is used to distinguish between connections and is added to the urls
437    */
438   struct GNUNET_CRYPTO_HashAsciiEncoded my_ascii_hash_ident;
439
440   /**
441    * IPv4 Address the plugin binds to
442    */
443   struct sockaddr_in * bind4_address;
444
445   /**
446    * IPv6 Address the plugins binds to
447    */
448   struct sockaddr_in6 * bind6_address;
449
450   /**
451    * Hostname to bind to
452    */
453   char * bind_hostname;
454
455   /**
456    * Is IPv4 enabled?
457    */
458   int use_ipv6;
459
460   /**
461    * Is IPv6 enabled?
462    */
463   int use_ipv4;
464
465   /**
466    * Closure passed by MHD to the mhd_logger function
467    */
468   void * mhd_log;
469
470   /* only needed for HTTPS plugin */
471 #if BUILD_HTTPS
472   /* The certificate MHD uses as an \0 terminated string */
473   char * cert;
474
475   /* The private key MHD uses as an \0 terminated string */
476   char * key;
477
478   /* crypto init string */
479   char * crypto_init;
480 #endif
481 };
482
483
484 /**
485  * Function called for a quick conversion of the binary address to
486  * a numeric address.  Note that the caller must not free the
487  * address and that the next call to this function is allowed
488  * to override the address again.
489  *
490  * @param cls closure
491  * @param addr binary address
492  * @param addrlen length of the address
493  * @return string representing the same address
494  */
495 static const char*
496 http_plugin_address_to_string (void *cls,
497                                    const void *addr,
498                                    size_t addrlen);
499
500
501 /**
502  * Call MHD to process pending ipv4 requests and then go back
503  * and schedule the next run.
504  */
505 static void http_server_daemon_v4_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
506 /**
507  * Call MHD to process pending ipv6 requests and then go back
508  * and schedule the next run.
509  */
510 static void http_server_daemon_v6_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
511
512 /**
513  * Function setting up curl handle and selecting message to send
514  * @param plugin plugin
515  * @param ses session to send data to
516  * @param con connection
517  * @return bytes sent to peer
518  */
519 static int send_check_connections (struct Plugin *plugin, struct Session *ps);
520
521 /**
522  * Function setting up file descriptors and scheduling task to run
523  * @param cls closure
524  * @param ses session to send data to
525  * @param
526  */
527 static int curl_schedule (struct Plugin *plugin);
528
529 /**
530  * Task scheduled to reset the inbound quota delay for a specific peer
531  * @param cls plugin as closure
532  * @param tc task context
533  */
534 static void reset_inbound_quota_delay (void *cls,
535                                        const struct GNUNET_SCHEDULER_TaskContext *tc)
536 {
537         struct HTTP_PeerContext * pc;
538
539         GNUNET_assert(cls !=NULL);
540
541         pc = (struct HTTP_PeerContext *) cls;
542         pc->reset_task = GNUNET_SCHEDULER_NO_TASK;
543
544         if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
545           return;
546
547         pc->delay = GNUNET_TIME_relative_get_zero ();
548 }
549
550
551 /**
552  * Creates a valid url from passed address and id
553  * @param plugin plugin
554  * @param addr address to create url from
555  * @param addrlen address lenth
556  * @param id session id
557  * @return the created url
558  */
559 static char * create_url(struct Plugin *plugin, const void * addr, size_t addrlen, size_t id)
560 {
561   char *url = NULL;
562   char *addr_str = (char *) http_plugin_address_to_string(NULL, addr, addrlen);
563
564   GNUNET_assert ((addr!=NULL) && (addrlen != 0));
565   GNUNET_asprintf(&url,
566                   "%s://%s/%s;%u", PROTOCOL_PREFIX, addr_str,
567                   (char *) (&plugin->my_ascii_hash_ident),id);
568   GNUNET_free_non_null(addr_str);
569   return url;
570 }
571
572 /**
573  * Removes a message from the linked list of messages
574  * @param ps session
575  * @param msg message
576  * @return GNUNET_SYSERR if msg not found, GNUNET_OK on success
577  */
578 static int remove_http_message (struct Session * ps, struct HTTP_Message * msg)
579 {
580   GNUNET_CONTAINER_DLL_remove(ps->pending_msgs_head,ps->pending_msgs_tail,msg);
581   GNUNET_free(msg);
582   return GNUNET_OK;
583 }
584
585 /**
586  * Iterator to remove peer context
587  * @param cls the plugin
588  * @param key the peers public key hashcode
589  * @param value the peer context
590  * @return GNUNET_YES on success
591  */
592 int remove_peer_context_Iterator (void *cls, const GNUNET_HashCode *key, void *value)
593 {
594   struct Plugin *plugin = cls;
595   struct HTTP_PeerContext * pc = value;
596   struct Session * ps = pc->head;
597   struct Session * tmp = NULL;
598   struct HTTP_Message * msg = NULL;
599   struct HTTP_Message * msg_tmp = NULL;
600 #if DEBUG_HTTP
601   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Freeing context for peer `%s'\n",GNUNET_i2s(&pc->identity));
602 #endif
603   GNUNET_CONTAINER_multihashmap_remove (plugin->peers, &pc->identity.hashPubKey, pc);
604   while (ps!=NULL)
605   {
606         plugin->env->session_end(plugin, &pc->identity, ps);
607         tmp = ps->next;
608
609     GNUNET_free_non_null (ps->addr);
610     GNUNET_free(ps->url);
611     if (ps->msgtok != NULL)
612       GNUNET_SERVER_mst_destroy (ps->msgtok);
613
614     msg = ps->pending_msgs_head;
615     while (msg!=NULL)
616     {
617       msg_tmp = msg->next;
618       GNUNET_free(msg);
619       msg = msg_tmp;
620     }
621     if (ps->direction==OUTBOUND)
622     {
623       if (ps->send_endpoint!=NULL)
624         curl_easy_cleanup(ps->send_endpoint);
625       if (ps->recv_endpoint!=NULL)
626         curl_easy_cleanup(ps->recv_endpoint);
627     }
628
629     GNUNET_free(ps);
630     ps=tmp;
631   }
632   GNUNET_free(pc);
633   GNUNET_STATISTICS_update (plugin->env->stats,
634                             gettext_noop ("# HTTP peers active"),
635                             -1,
636                             GNUNET_NO);
637   return GNUNET_YES;
638 }
639
640
641 /**
642  * Removes a session from the linked list of sessions
643  * @param pc peer context
644  * @param ps session
645  * @param call_msg_cont GNUNET_YES to call pending message continuations, otherwise no
646  * @param call_msg_cont_result result to call message continuations with
647  * @return GNUNET_SYSERR if msg not found, GNUNET_OK on success
648  */
649 static int remove_session (struct HTTP_PeerContext * pc, struct Session * ps,  int call_msg_cont, int call_msg_cont_result)
650 {
651   struct HTTP_Message * msg;
652   struct Plugin * plugin = ps->peercontext->plugin;
653
654 #if DEBUG_CONNECTIONS
655   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: removing %s session %X with id %u\n", ps, (ps->direction == INBOUND) ? "inbound" : "outbound", ps, ps->session_id);
656 #endif
657   plugin->env->session_end(plugin, &pc->identity, ps);
658
659   GNUNET_free_non_null (ps->addr);
660   GNUNET_SERVER_mst_destroy (ps->msgtok);
661   GNUNET_free(ps->url);
662
663   if (ps->direction==INBOUND)
664   {
665           if (ps->recv_endpoint != NULL)
666           {
667                   curl_easy_cleanup(ps->recv_endpoint);
668                   ps->recv_endpoint = NULL;
669           }
670           if (ps->send_endpoint != NULL)
671           {
672                   curl_easy_cleanup(ps->send_endpoint);
673                   ps->send_endpoint = NULL;
674           }
675   }
676
677   msg = ps->pending_msgs_head;
678   while (msg!=NULL)
679   {
680     if ((call_msg_cont == GNUNET_YES) && (msg->transmit_cont!=NULL))
681     {
682       msg->transmit_cont (msg->transmit_cont_cls,&pc->identity,call_msg_cont_result);
683     }
684     GNUNET_CONTAINER_DLL_remove(ps->pending_msgs_head,ps->pending_msgs_head,msg);
685     GNUNET_free(msg);
686     msg = ps->pending_msgs_head;
687   }
688
689   GNUNET_CONTAINER_DLL_remove(pc->head,pc->tail,ps);
690   GNUNET_free(ps);
691   ps = NULL;
692
693   /* no sessions left remove peer */
694   if (pc->head==NULL)
695   {
696 #if DEBUG_HTTP
697   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"No sessions left for peer `%s', removing context\n",GNUNET_i2s(&pc->identity));
698 #endif
699         remove_peer_context_Iterator(plugin, &pc->identity.hashPubKey, pc);
700   }
701
702   return GNUNET_OK;
703 }
704
705
706 /**
707  * Add the IP of our network interface to the list of
708  * our external IP addresses.
709  *
710  * @param cls the 'struct Plugin*'
711  * @param name name of the interface
712  * @param isDefault do we think this may be our default interface
713  * @param addr address of the interface
714  * @param addrlen number of bytes in addr
715  * @return GNUNET_OK to continue iterating
716  */
717 static int
718 process_interfaces (void *cls,
719                     const char *name,
720                     int isDefault,
721                     const struct sockaddr *addr, socklen_t addrlen)
722 {
723   struct Plugin *plugin = cls;
724   struct IPv4HttpAddress * t4;
725   struct IPv6HttpAddress * t6;
726   int af;
727
728
729   GNUNET_assert(cls !=NULL);
730   af = addr->sa_family;
731   if ((af == AF_INET) && (plugin->use_ipv4 == GNUNET_YES) && (plugin->bind6_address == NULL))
732     {
733           struct in_addr bnd_cmp = ((struct sockaddr_in *) addr)->sin_addr;
734       t4 = GNUNET_malloc(sizeof(struct IPv4HttpAddress));
735       /* Not skipping loopback addresses
736       if (INADDR_LOOPBACK == ntohl(((struct sockaddr_in *) addr)->sin_addr.s_addr))
737       {
738
739         return GNUNET_OK;
740       }
741       */
742       t4->ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
743       t4->u_port = htons (plugin->port_inbound);
744       if (plugin->bind4_address != NULL)
745       {
746           if (0 == memcmp(&plugin->bind4_address->sin_addr, &bnd_cmp, sizeof (struct in_addr)))
747           {
748               GNUNET_CONTAINER_DLL_insert(plugin->ipv4_addr_head,plugin->ipv4_addr_tail,t4);
749                   plugin->env->notify_address(plugin->env->cls,PROTOCOL_PREFIX,t4, sizeof (struct IPv4HttpAddress), GNUNET_TIME_UNIT_FOREVER_REL);
750                   return GNUNET_OK;
751           }
752                   GNUNET_free (t4);
753                   return GNUNET_OK;
754       }
755       else
756       {
757           GNUNET_CONTAINER_DLL_insert(plugin->ipv4_addr_head,plugin->ipv4_addr_tail,t4);
758           plugin->env->notify_address(plugin->env->cls,PROTOCOL_PREFIX,t4, sizeof (struct IPv4HttpAddress), GNUNET_TIME_UNIT_FOREVER_REL);
759           return GNUNET_OK;
760       }
761     }
762   else if ((af == AF_INET6) && (plugin->use_ipv6 == GNUNET_YES)  && (plugin->bind4_address == NULL))
763     {
764           struct in6_addr bnd_cmp6 = ((struct sockaddr_in6 *) addr)->sin6_addr;
765       if (IN6_IS_ADDR_LINKLOCAL (&((struct sockaddr_in6 *) addr)->sin6_addr))
766         {
767           return GNUNET_OK;
768         }
769       t6 = GNUNET_malloc(sizeof(struct IPv6HttpAddress));
770       GNUNET_assert(t6 != NULL);
771       if (plugin->bind6_address != NULL)
772       {
773           if (0 == memcmp(&plugin->bind6_address->sin6_addr, &bnd_cmp6, sizeof (struct in6_addr)))
774           {
775               memcpy (&t6->ipv6_addr,
776                       &((struct sockaddr_in6 *) addr)->sin6_addr,
777                       sizeof (struct in6_addr));
778               t6->u6_port = htons (plugin->port_inbound);
779               plugin->env->notify_address(plugin->env->cls,PROTOCOL_PREFIX,t6,sizeof (struct IPv6HttpAddress) , GNUNET_TIME_UNIT_FOREVER_REL);
780               GNUNET_CONTAINER_DLL_insert(plugin->ipv6_addr_head,plugin->ipv6_addr_tail,t6);
781                   return GNUNET_OK;
782           }
783                   GNUNET_free (t6);
784                   return GNUNET_OK;
785       }
786           memcpy (&t6->ipv6_addr,
787                           &((struct sockaddr_in6 *) addr)->sin6_addr,
788                           sizeof (struct in6_addr));
789           t6->u6_port = htons (plugin->port_inbound);
790           GNUNET_CONTAINER_DLL_insert(plugin->ipv6_addr_head,plugin->ipv6_addr_tail,t6);
791           plugin->env->notify_address(plugin->env->cls,PROTOCOL_PREFIX,t6,sizeof (struct IPv6HttpAddress) , GNUNET_TIME_UNIT_FOREVER_REL);
792     }
793   return GNUNET_OK;
794 }
795
796
797 /**
798  * External logging function for MHD
799  * @param arg arguments
800  * @param fmt format string
801  * @param ap  list of arguments
802  */
803 void mhd_logger (void * arg, const char * fmt, va_list ap)
804 {
805         char text[1024];
806         vsnprintf(text, 1024, fmt, ap);
807         va_end(ap);
808         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,"MHD: %s \n", text);
809 }
810
811
812 static void mhd_termination_cb (void *cls, struct MHD_Connection * connection, void **httpSessionCache)
813 {
814   struct Session * ps = *httpSessionCache;
815   if (ps == NULL)
816     return;
817   struct HTTP_PeerContext * pc = ps->peercontext;
818         
819   if (connection==ps->recv_endpoint)
820   {
821 #if DEBUG_CONNECTIONS
822     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: inbound connection from peer `%s' was terminated\n", ps, GNUNET_i2s(&pc->identity));
823 #endif
824     ps->recv_active = GNUNET_NO;
825     ps->recv_connected = GNUNET_NO;
826     ps->recv_endpoint = NULL;
827   }
828   if (connection==ps->send_endpoint)
829   {
830
831     ps->send_active = GNUNET_NO;
832     ps->send_connected = GNUNET_NO;
833     ps->send_endpoint = NULL;
834 #if DEBUG_CONNECTIONS
835     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: outbound connection from peer `%s' was terminated\n", ps, GNUNET_i2s(&pc->identity));
836 #endif
837   }
838
839   /* if both connections disconnected, remove session */
840   if ((ps->send_connected == GNUNET_NO) && (ps->recv_connected == GNUNET_NO))
841   {
842       GNUNET_STATISTICS_update (pc->plugin->env->stats,
843                             gettext_noop ("# HTTP inbound sessions for peers active"),
844                             -1,
845                             GNUNET_NO);
846     remove_session(pc,ps,GNUNET_YES,GNUNET_SYSERR);
847   }
848 }
849
850 /**
851  * Callback called by MessageStreamTokenizer when a message has arrived
852  * @param cls current session as closure
853  * @param client clien
854  * @param message the message to be forwarded to transport service
855  */
856
857 static void mhd_write_mst_cb (void *cls,
858                               void *client,
859                               const struct GNUNET_MessageHeader *message)
860 {
861   struct GNUNET_TIME_Relative delay;
862   struct Session *ps  = cls;
863   GNUNET_assert(ps != NULL);
864
865   struct HTTP_PeerContext *pc = ps->peercontext;
866   GNUNET_assert(pc != NULL);
867 #if DEBUG_HTTP
868   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
869               "Connection %X: Forwarding message to transport service, type %u and size %u from `%s' (`%s')\n",
870               ps,
871               ntohs(message->type),
872               ntohs(message->size),
873               GNUNET_i2s(&(ps->peercontext)->identity),http_plugin_address_to_string(NULL,ps->addr,ps->addrlen));
874 #endif
875   delay = pc->plugin->env->receive (ps->peercontext->plugin->env->cls,
876                                                                                                                   &pc->identity,
877                                                                                                                   message, 1, ps,
878                                                                                                                   NULL,
879                                                                                                                   0);
880   pc->delay = delay;
881   if (pc->reset_task != GNUNET_SCHEDULER_NO_TASK)
882         GNUNET_SCHEDULER_cancel (pc->plugin->env->sched, pc->reset_task);
883
884   if (delay.value > 0)
885   {
886 #if DEBUG_HTTP
887         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,"Connection %X: Inbound quota management: delay next read for %llu ms \n", ps, delay.value);
888 #endif
889         pc->reset_task = GNUNET_SCHEDULER_add_delayed (pc->plugin->env->sched, delay, &reset_inbound_quota_delay, pc);
890   }
891 }
892
893 /**
894  * Check if incoming connection is accepted.
895  * NOTE: Here every connection is accepted
896  * @param cls plugin as closure
897  * @param addr address of incoming connection
898  * @param addr_len address length of incoming connection
899  * @return MHD_YES if connection is accepted, MHD_NO if connection is rejected
900  *
901  */
902 static int
903 mhd_accept_cb (void *cls, const struct sockaddr *addr, socklen_t addr_len)
904 {
905 #if 0
906   struct Plugin *plugin = cls;
907 #endif
908   /* Every connection is accepted, nothing more to do here */
909   return MHD_YES;
910 }
911
912
913 /**
914  * Callback called by MHD when it needs data to send
915  * @param cls current session
916  * @param pos position in buffer
917  * @param buf the buffer to write data to
918  * @param max max number of bytes available in buffer
919  * @return bytes written to buffer
920  */
921 static ssize_t
922 mhd_send_callback (void *cls, uint64_t pos, char *buf, size_t max)
923 {
924   struct Session * ps = cls;
925   struct HTTP_PeerContext * pc;
926   struct HTTP_Message * msg;
927   int bytes_read = 0;
928
929   GNUNET_assert (ps!=NULL);
930
931   pc = ps->peercontext;
932   msg = ps->pending_msgs_tail;
933   if (ps->send_force_disconnect==GNUNET_YES)
934   {
935 #if DEBUG_CONNECTIONS
936     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: outbound forced to disconnect\n",ps);
937 #endif
938     return -1;
939   }
940
941   if (msg!=NULL)
942   {
943     if ((msg->size-msg->pos) <= max)
944     {
945       memcpy(buf,&msg->buf[msg->pos],(msg->size-msg->pos));
946       bytes_read = msg->size-msg->pos;
947       msg->pos+=(msg->size-msg->pos);
948     }
949     else
950     {
951       memcpy(buf,&msg->buf[msg->pos],max);
952       msg->pos+=max;
953       bytes_read = max;
954     }
955
956     if (msg->pos==msg->size)
957     {
958       if (NULL!=msg->transmit_cont)
959         msg->transmit_cont (msg->transmit_cont_cls,&pc->identity,GNUNET_OK);
960       ps->queue_length_cur -= msg->size;
961       remove_http_message(ps,msg);
962     }
963   }
964   return bytes_read;
965 }
966
967 /**
968  * Process GET or PUT request received via MHD.  For
969  * GET, queue response that will send back our pending
970  * messages.  For PUT, process incoming data and send
971  * to GNUnet core.  In either case, check if a session
972  * already exists and create a new one if not.
973  */
974 static int
975 mdh_access_cb (void *cls,
976                            struct MHD_Connection *mhd_connection,
977                            const char *url,
978                            const char *method,
979                            const char *version,
980                            const char *upload_data,
981                            size_t * upload_data_size, void **httpSessionCache)
982 {
983   struct Plugin *plugin = cls;
984   struct MHD_Response *response;
985   const union MHD_ConnectionInfo * conn_info;
986
987   struct sockaddr_in  *addrin;
988   struct sockaddr_in6 *addrin6;
989
990   char address[INET6_ADDRSTRLEN+14];
991   struct GNUNET_PeerIdentity pi_in;
992   size_t id_num = 0;
993
994   struct IPv4HttpAddress ipv4addr;
995   struct IPv6HttpAddress ipv6addr;
996
997   struct HTTP_PeerContext *pc = NULL;
998   struct Session *ps = NULL;
999   struct Session *ps_tmp = NULL;
1000
1001   int res = GNUNET_NO;
1002   int send_error_to_client;
1003   void * addr = NULL;
1004   size_t addr_len = 0 ;
1005
1006   GNUNET_assert(cls !=NULL);
1007   send_error_to_client = GNUNET_NO;
1008
1009   if (NULL == *httpSessionCache)
1010   {
1011     /* check url for peer identity , if invalid send HTTP 404*/
1012     size_t len = strlen(&url[1]);
1013     char * peer = GNUNET_malloc(104+1);
1014
1015     if ((len>104) && (url[104]==';'))
1016     {
1017         char * id = GNUNET_malloc((len-104)+1);
1018         strcpy(id,&url[105]);
1019         memcpy(peer,&url[1],103);
1020         peer[103] = '\0';
1021         id_num = strtoul ( id, NULL , 10);
1022         GNUNET_free(id);
1023     }
1024     res = GNUNET_CRYPTO_hash_from_string (peer, &(pi_in.hashPubKey));
1025     GNUNET_free(peer);
1026     if ( GNUNET_SYSERR == res )
1027     {
1028       response = MHD_create_response_from_data (strlen (HTTP_ERROR_RESPONSE),HTTP_ERROR_RESPONSE, MHD_NO, MHD_NO);
1029       res = MHD_queue_response (mhd_connection, MHD_HTTP_NOT_FOUND, response);
1030       MHD_destroy_response (response);
1031 #if DEBUG_CONNECTIONS
1032       if (res == MHD_YES)
1033         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Peer has no valid ident, sent HTTP 1.1/404\n");
1034       else
1035         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Peer has no valid ident, could not send error\n");
1036 #endif
1037       return res;
1038     }
1039   }
1040   else
1041   {
1042     ps = *httpSessionCache;
1043     pc = ps->peercontext;
1044   }
1045
1046   if (NULL == *httpSessionCache)
1047   {
1048     /* get peer context */
1049     pc = GNUNET_CONTAINER_multihashmap_get (plugin->peers, &pi_in.hashPubKey);
1050     /* Peer unknown */
1051     if (pc==NULL)
1052     {
1053       pc = GNUNET_malloc(sizeof (struct HTTP_PeerContext));
1054       pc->plugin = plugin;
1055       pc->session_id_counter=1;
1056       pc->last_session = NULL;
1057       memcpy(&pc->identity, &pi_in, sizeof(struct GNUNET_PeerIdentity));
1058       GNUNET_CONTAINER_multihashmap_put(plugin->peers, &pc->identity.hashPubKey, pc, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1059       GNUNET_STATISTICS_update (plugin->env->stats,
1060                             gettext_noop ("# HTTP peers active"),
1061                             1,
1062                             GNUNET_NO);
1063     }
1064
1065     conn_info = MHD_get_connection_info(mhd_connection, MHD_CONNECTION_INFO_CLIENT_ADDRESS );
1066     /* Incoming IPv4 connection */
1067     if ( AF_INET == conn_info->client_addr->sin_family)
1068     {
1069       addrin = conn_info->client_addr;
1070       inet_ntop(addrin->sin_family, &(addrin->sin_addr),address,INET_ADDRSTRLEN);
1071       memcpy(&ipv4addr.ipv4_addr,&(addrin->sin_addr),sizeof(struct in_addr));
1072       ipv4addr.u_port = addrin->sin_port;
1073       addr = &ipv4addr;
1074       addr_len = sizeof(struct IPv4HttpAddress);
1075     }
1076     /* Incoming IPv6 connection */
1077     if ( AF_INET6 == conn_info->client_addr->sin_family)
1078     {
1079       addrin6 = (struct sockaddr_in6 *) conn_info->client_addr;
1080       inet_ntop(addrin6->sin6_family, &(addrin6->sin6_addr),address,INET6_ADDRSTRLEN);
1081       memcpy(&ipv6addr.ipv6_addr,&(addrin6->sin6_addr),sizeof(struct in6_addr));
1082       ipv6addr.u6_port = addrin6->sin6_port;
1083       addr = &ipv6addr;
1084       addr_len = sizeof(struct IPv6HttpAddress);
1085     }
1086
1087     GNUNET_assert (addr != NULL);
1088     GNUNET_assert (addr_len != 0);
1089
1090     ps = NULL;
1091     /* only inbound sessions here */
1092
1093     ps_tmp = pc->head;
1094     while (ps_tmp!=NULL)
1095     {
1096       if ((ps_tmp->direction==INBOUND) && (ps_tmp->session_id == id_num) && (id_num!=0))
1097       {
1098         if ((ps_tmp->recv_force_disconnect!=GNUNET_YES) && (ps_tmp->send_force_disconnect!=GNUNET_YES))
1099         ps=ps_tmp;
1100         break;
1101       }
1102       ps_tmp=ps_tmp->next;
1103     }
1104
1105     if (ps==NULL)
1106     {
1107       ps = GNUNET_malloc(sizeof (struct Session));
1108       ps->addr = GNUNET_malloc(addr_len);
1109       memcpy(ps->addr,addr,addr_len);
1110       ps->addrlen = addr_len;
1111       ps->direction=INBOUND;
1112       ps->pending_msgs_head = NULL;
1113       ps->pending_msgs_tail = NULL;
1114       ps->send_connected=GNUNET_NO;
1115       ps->send_active=GNUNET_NO;
1116       ps->recv_connected=GNUNET_NO;
1117       ps->recv_active=GNUNET_NO;
1118       ps->peercontext=pc;
1119       ps->session_id =id_num;
1120           ps->queue_length_cur = 0;
1121           ps->queue_length_max = GNUNET_SERVER_MAX_MESSAGE_SIZE;
1122       ps->url = create_url (plugin, ps->addr, ps->addrlen, ps->session_id);
1123       GNUNET_CONTAINER_DLL_insert(pc->head,pc->tail,ps);
1124       GNUNET_STATISTICS_update (plugin->env->stats,
1125                             gettext_noop ("# HTTP inbound sessions for peers active"),
1126                             1,
1127                             GNUNET_NO);
1128     }
1129
1130     *httpSessionCache = ps;
1131     if (ps->msgtok==NULL)
1132       ps->msgtok = GNUNET_SERVER_mst_create (&mhd_write_mst_cb, ps);
1133 #if DEBUG_HTTP
1134     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: HTTP Daemon has new an incoming `%s' request from peer `%s' (`%s')\n",
1135                 ps,
1136                 method,
1137                 GNUNET_i2s(&pc->identity),
1138                 http_plugin_address_to_string(NULL, ps->addr, ps->addrlen));
1139 #endif
1140   }
1141
1142   /* Is it a PUT or a GET request */
1143   if (0 == strcmp (MHD_HTTP_METHOD_PUT, method))
1144   {
1145     if (ps->recv_force_disconnect == GNUNET_YES)
1146     {
1147 #if DEBUG_CONNECTIONS
1148       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: inbound connection was forced to disconnect\n",ps);
1149 #endif
1150       ps->recv_active = GNUNET_NO;
1151       return MHD_NO;
1152     }
1153     if ((*upload_data_size == 0) && (ps->recv_active==GNUNET_NO))
1154     {
1155       ps->recv_endpoint = mhd_connection;
1156       ps->recv_connected = GNUNET_YES;
1157       ps->recv_active = GNUNET_YES;
1158       ps->recv_force_disconnect = GNUNET_NO;
1159 #if DEBUG_CONNECTIONS
1160       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: inbound PUT connection connected\n",ps);
1161 #endif
1162       return MHD_YES;
1163     }
1164
1165     /* Transmission of all data complete */
1166     if ((*upload_data_size == 0) && (ps->recv_active == GNUNET_YES))
1167     {
1168       response = MHD_create_response_from_data (strlen (HTTP_PUT_RESPONSE),HTTP_PUT_RESPONSE, MHD_NO, MHD_NO);
1169       res = MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
1170 #if DEBUG_CONNECTIONS
1171       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: Sent HTTP/1.1: 200 OK as PUT Response\n",ps);
1172 #endif
1173       MHD_destroy_response (response);
1174       ps->recv_active=GNUNET_NO;
1175       return MHD_YES;
1176     }
1177
1178     /* Recieving data */
1179     if ((*upload_data_size > 0) && (ps->recv_active == GNUNET_YES))
1180     {
1181       if (pc->delay.value == 0)
1182       {
1183                   res = GNUNET_SERVER_mst_receive(ps->msgtok, ps, upload_data,*upload_data_size, GNUNET_NO, GNUNET_NO);
1184                   (*upload_data_size) = 0;
1185       }
1186       else
1187       {
1188 #if DEBUG_HTTP
1189           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: no inbound bandwidth available! Next read was delayed for  %llu ms\n", ps, ps->peercontext->delay.value);
1190 #endif
1191       }
1192       return MHD_YES;
1193     }
1194     else
1195       return MHD_NO;
1196   }
1197   if ( 0 == strcmp (MHD_HTTP_METHOD_GET, method) )
1198   {
1199     if (ps->send_force_disconnect == GNUNET_YES)
1200     {
1201 #if DEBUG_CONNECTIONS
1202       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: outbound connection was  forced to disconnect\n",ps);
1203 #endif
1204       ps->send_active = GNUNET_NO;
1205       return MHD_NO;
1206     }
1207           ps->send_connected = GNUNET_YES;
1208           ps->send_active = GNUNET_YES;
1209           ps->send_endpoint = mhd_connection;
1210           ps->send_force_disconnect = GNUNET_NO;
1211 #if DEBUG_CONNECTIONS
1212           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: inbound GET connection connected\n",ps);
1213 #endif
1214           response = MHD_create_response_from_callback(-1,32 * 1024, &mhd_send_callback, ps, NULL);
1215           res = MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
1216           MHD_destroy_response (response);
1217           return MHD_YES;
1218   }
1219   return MHD_NO;
1220 }
1221
1222 /**
1223  * Function that queries MHD's select sets and
1224  * starts the task waiting for them.
1225  * @param plugin plugin
1226  * @param daemon_handle the MHD daemon handle
1227  * @return gnunet task identifier
1228  */
1229 static GNUNET_SCHEDULER_TaskIdentifier
1230 http_server_daemon_prepare (struct Plugin *plugin , struct MHD_Daemon *daemon_handle)
1231 {
1232   GNUNET_SCHEDULER_TaskIdentifier ret;
1233   fd_set rs;
1234   fd_set ws;
1235   fd_set es;
1236   struct GNUNET_NETWORK_FDSet *wrs;
1237   struct GNUNET_NETWORK_FDSet *wws;
1238   struct GNUNET_NETWORK_FDSet *wes;
1239   int max;
1240   unsigned long long timeout;
1241   int haveto;
1242   struct GNUNET_TIME_Relative tv;
1243
1244   ret = GNUNET_SCHEDULER_NO_TASK;
1245   FD_ZERO(&rs);
1246   FD_ZERO(&ws);
1247   FD_ZERO(&es);
1248   wrs = GNUNET_NETWORK_fdset_create ();
1249   wes = GNUNET_NETWORK_fdset_create ();
1250   wws = GNUNET_NETWORK_fdset_create ();
1251   max = -1;
1252   GNUNET_assert (MHD_YES ==
1253                  MHD_get_fdset (daemon_handle,
1254                                 &rs,
1255                                 &ws,
1256                                 &es,
1257                                 &max));
1258   haveto = MHD_get_timeout (daemon_handle, &timeout);
1259   if (haveto == MHD_YES)
1260     tv.value = (uint64_t) timeout;
1261   else
1262     tv = GNUNET_TIME_UNIT_SECONDS;
1263   GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max);
1264   GNUNET_NETWORK_fdset_copy_native (wws, &ws, max);
1265   GNUNET_NETWORK_fdset_copy_native (wes, &es, max);
1266   if (daemon_handle == plugin->http_server_daemon_v4)
1267   {
1268         if (plugin->http_server_task_v4 != GNUNET_SCHEDULER_NO_TASK)
1269         {
1270                 GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_server_task_v4);
1271                 plugin->http_server_daemon_v4 = GNUNET_SCHEDULER_NO_TASK;
1272         }
1273
1274     ret = GNUNET_SCHEDULER_add_select (plugin->env->sched,
1275                                        GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1276                                        GNUNET_SCHEDULER_NO_TASK,
1277                                        tv,
1278                                        wrs,
1279                                        wws,
1280                                        &http_server_daemon_v4_run,
1281                                        plugin);
1282   }
1283   if (daemon_handle == plugin->http_server_daemon_v6)
1284   {
1285         if (plugin->http_server_task_v6 != GNUNET_SCHEDULER_NO_TASK)
1286         {
1287                 GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_server_task_v6);
1288                 plugin->http_server_task_v6 = GNUNET_SCHEDULER_NO_TASK;
1289         }
1290
1291     ret = GNUNET_SCHEDULER_add_select (plugin->env->sched,
1292                                        GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1293                                        GNUNET_SCHEDULER_NO_TASK,
1294                                        tv,
1295                                        wrs,
1296                                        wws,
1297                                        &http_server_daemon_v6_run,
1298                                        plugin);
1299   }
1300   GNUNET_NETWORK_fdset_destroy (wrs);
1301   GNUNET_NETWORK_fdset_destroy (wws);
1302   GNUNET_NETWORK_fdset_destroy (wes);
1303   return ret;
1304 }
1305
1306 /**
1307  * Call MHD IPv4 to process pending requests and then go back
1308  * and schedule the next run.
1309  * @param cls plugin as closure
1310  * @param tc task context
1311  */
1312 static void http_server_daemon_v4_run (void *cls,
1313                              const struct GNUNET_SCHEDULER_TaskContext *tc)
1314 {
1315   struct Plugin *plugin = cls;
1316
1317 #if DEBUG_SCHEDULING
1318   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY))
1319     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,"http_server_daemon_v4_run: GNUNET_SCHEDULER_REASON_READ_READY\n");      
1320   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) 
1321       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,"http_server_daemon_v4_run: GNUNET_SCHEDULER_REASON_WRITE_READY\n");  
1322   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1323       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,"http_server_daemon_v4_run: GNUNET_SCHEDULER_REASON_TIMEOUT\n");
1324   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_STARTUP))
1325       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,"http_server_daemon_v4_run: GGNUNET_SCHEDULER_REASON_STARTUP\n");        
1326   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1327       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,"http_server_daemon_v4_run: GGNUNET_SCHEDULER_REASON_SHUTDOWN\n");                 
1328 #endif              
1329       
1330   GNUNET_assert(cls !=NULL);
1331   plugin->http_server_task_v4 = GNUNET_SCHEDULER_NO_TASK;
1332
1333   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1334     return;
1335
1336   GNUNET_assert (MHD_YES == MHD_run (plugin->http_server_daemon_v4));
1337   plugin->http_server_task_v4 = http_server_daemon_prepare (plugin, plugin->http_server_daemon_v4);
1338  }
1339
1340
1341 /**
1342  * Call MHD IPv6 to process pending requests and then go back
1343  * and schedule the next run.
1344  * @param cls plugin as closure
1345  * @param tc task context
1346  */
1347 static void http_server_daemon_v6_run (void *cls,
1348                              const struct GNUNET_SCHEDULER_TaskContext *tc)
1349 {
1350   struct Plugin *plugin = cls;
1351   
1352 #if DEBUG_SCHEDULING  
1353   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY))
1354       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,"http_server_daemon_v6_run: GNUNET_SCHEDULER_REASON_READ_READY\n");
1355   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) 
1356       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,"http_server_daemon_v6_run: GNUNET_SCHEDULER_REASON_WRITE_READY\n");
1357   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1358       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,"http_server_daemon_v6_run: GNUNET_SCHEDULER_REASON_TIMEOUT\n");
1359   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_STARTUP))  
1360      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,"http_server_daemon_v6_run: GGNUNET_SCHEDULER_REASON_STARTUP\n");    
1361   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))  
1362      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,"http_server_daemon_v6_run: GGNUNET_SCHEDULER_REASON_SHUTDOWN\n"); 
1363 #endif                                            
1364
1365   GNUNET_assert(cls !=NULL);
1366   plugin->http_server_task_v6 = GNUNET_SCHEDULER_NO_TASK;
1367
1368   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1369     return;
1370
1371   GNUNET_assert (MHD_YES == MHD_run (plugin->http_server_daemon_v6));
1372   plugin->http_server_task_v6 = http_server_daemon_prepare (plugin, plugin->http_server_daemon_v6);
1373 }
1374
1375 static size_t curl_get_header_cb( void *ptr, size_t size, size_t nmemb, void *stream)
1376 {
1377   struct Session * ps = stream;
1378
1379   long http_result = 0;
1380   int res;
1381   /* Getting last http result code */
1382   GNUNET_assert(NULL!=ps);
1383   if (ps->recv_connected==GNUNET_NO)
1384   {
1385     res = curl_easy_getinfo(ps->recv_endpoint, CURLINFO_RESPONSE_CODE, &http_result);
1386     if (CURLE_OK == res)
1387     {
1388       if (http_result == 200)
1389       {
1390         ps->recv_connected = GNUNET_YES;
1391         ps->recv_active = GNUNET_YES;
1392 #if DEBUG_CONNECTIONS
1393         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: connected to recieve data\n",ps);
1394 #endif
1395         // Calling send_check_connections again since receive is established
1396         send_check_connections (ps->peercontext->plugin, ps);
1397       }
1398     }
1399   }
1400
1401 #if DEBUG_CURL
1402   char * tmp;
1403   size_t len = size * nmemb;
1404   tmp = NULL;
1405   if ((size * nmemb) < SIZE_MAX)
1406     tmp = GNUNET_malloc (len+1);
1407
1408   if ((tmp != NULL) && (len > 0))
1409   {
1410     memcpy(tmp,ptr,len);
1411     if (len>=2)
1412     {
1413       if (tmp[len-2] == 13)
1414         tmp[len-2]= '\0';
1415     }
1416     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: Header: %s\n",ps,tmp);
1417   }
1418   GNUNET_free_non_null (tmp);
1419 #endif
1420
1421   return size * nmemb;
1422 }
1423
1424 /**
1425  * Callback called by libcurl when new headers arrive
1426  * Used to get HTTP result for curl operations
1427  * @param ptr stream to read from
1428  * @param size size of one char element
1429  * @param nmemb number of char elements
1430  * @param stream closure set by user
1431  * @return bytes read by function
1432  */
1433
1434 static size_t curl_put_header_cb( void *ptr, size_t size, size_t nmemb, void *stream)
1435 {
1436   struct Session * ps = stream;
1437
1438   char * tmp;
1439   size_t len = size * nmemb;
1440   long http_result = 0;
1441   int res;
1442
1443   /* Getting last http result code */
1444   GNUNET_assert(NULL!=ps);
1445   res = curl_easy_getinfo(ps->send_endpoint, CURLINFO_RESPONSE_CODE, &http_result);
1446   if (CURLE_OK == res)
1447   {
1448     if ((http_result == 100) && (ps->send_connected==GNUNET_NO))
1449     {
1450       ps->send_connected = GNUNET_YES;
1451       ps->send_active = GNUNET_YES;
1452 #if DEBUG_CONNECTIONS
1453       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: connected to send data\n",ps);
1454 #endif
1455     }
1456     if ((http_result == 200) && (ps->send_connected==GNUNET_YES))
1457     {
1458       ps->send_connected = GNUNET_NO;
1459       ps->send_active = GNUNET_NO;
1460 #if DEBUG_CONNECTIONS
1461       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: sending disconnected\n",ps);
1462 #endif
1463     }
1464   }
1465
1466   tmp = NULL;
1467   if ((size * nmemb) < SIZE_MAX)
1468     tmp = GNUNET_malloc (len+1);
1469
1470   if ((tmp != NULL) && (len > 0))
1471   {
1472     memcpy(tmp,ptr,len);
1473     if (len>=2)
1474     {
1475       if (tmp[len-2] == 13)
1476         tmp[len-2]= '\0';
1477     }
1478   }
1479
1480   GNUNET_free_non_null (tmp);
1481
1482   return size * nmemb;
1483 }
1484
1485 /**
1486  * Callback method used with libcurl
1487  * Method is called when libcurl needs to read data during sending
1488  * @param stream pointer where to write data
1489  * @param size size of an individual element
1490  * @param nmemb count of elements that can be written to the buffer
1491  * @param ptr source pointer, passed to the libcurl handle
1492  * @return bytes written to stream
1493  */
1494 static size_t curl_send_cb(void *stream, size_t size, size_t nmemb, void *ptr)
1495 {
1496   struct Session * ps = ptr;
1497   struct HTTP_Message * msg = ps->pending_msgs_tail;
1498   size_t bytes_sent;
1499   size_t len;
1500
1501   if (ps->send_active == GNUNET_NO)
1502   {
1503         return CURL_READFUNC_PAUSE;
1504   }
1505
1506   if ((ps->pending_msgs_tail == NULL) && (ps->send_active == GNUNET_YES))
1507   {
1508 #if DEBUG_CONNECTIONS
1509     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: No Message to send, pausing connection\n",ps);
1510 #endif
1511     ps->send_active = GNUNET_NO;
1512     return CURL_READFUNC_PAUSE;
1513   }
1514
1515   GNUNET_assert (msg!=NULL);
1516
1517   /* data to send */
1518   if (msg->pos < msg->size)
1519   {
1520     /* data fit in buffer */
1521     if ((msg->size - msg->pos) <= (size * nmemb))
1522     {
1523       len = (msg->size - msg->pos);
1524       memcpy(stream, &msg->buf[msg->pos], len);
1525       msg->pos += len;
1526       bytes_sent = len;
1527     }
1528     else
1529     {
1530       len = size*nmemb;
1531       memcpy(stream, &msg->buf[msg->pos], len);
1532       msg->pos += len;
1533       bytes_sent = len;
1534     }
1535   }
1536   /* no data to send */
1537   else
1538   {
1539     bytes_sent = 0;
1540   }
1541
1542   if ( msg->pos == msg->size)
1543   {
1544 #if DEBUG_CONNECTIONS
1545           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,"Connection %X: Message with %u bytes sent, removing message from queue \n",ps, msg->pos);
1546 #endif
1547     /* Calling transmit continuation  */
1548     if (NULL != ps->pending_msgs_tail->transmit_cont)
1549       msg->transmit_cont (ps->pending_msgs_tail->transmit_cont_cls,&(ps->peercontext)->identity,GNUNET_OK);
1550     ps->queue_length_cur -= msg->size;
1551     remove_http_message(ps, msg);
1552   }
1553   return bytes_sent;
1554 }
1555
1556 static void curl_receive_mst_cb  (void *cls,
1557                                 void *client,
1558                                 const struct GNUNET_MessageHeader *message)
1559 {
1560   struct Session *ps  = cls;
1561   struct GNUNET_TIME_Relative delay;
1562   GNUNET_assert(ps != NULL);
1563
1564   struct HTTP_PeerContext *pc = ps->peercontext;
1565   GNUNET_assert(pc != NULL);
1566 #if DEBUG_HTTP
1567   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1568               "Connection %X: Forwarding message to transport service, type %u and size %u from `%s' (`%s')\n",
1569               ps,
1570               ntohs(message->type),
1571               ntohs(message->size),
1572               GNUNET_i2s(&(pc->identity)),http_plugin_address_to_string(NULL,ps->addr,ps->addrlen));
1573 #endif
1574   delay = pc->plugin->env->receive (pc->plugin->env->cls,
1575                                                                   &pc->identity,
1576                                                               message, 1, ps,
1577                                                               ps->addr,
1578                                                               ps->addrlen);
1579
1580   pc->delay = delay;
1581   if (pc->reset_task != GNUNET_SCHEDULER_NO_TASK)
1582         GNUNET_SCHEDULER_cancel (pc->plugin->env->sched, pc->reset_task);
1583
1584   if (delay.value > 0)
1585   {
1586 #if DEBUG_HTTP
1587         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,"Connection %X: Inbound quota management: delay next read for %llu ms \n", ps, delay.value);
1588 #endif
1589         pc->reset_task = GNUNET_SCHEDULER_add_delayed (pc->plugin->env->sched, delay, &reset_inbound_quota_delay, pc);
1590   }
1591 }
1592
1593
1594 /**
1595 * Callback method used with libcurl
1596 * Method is called when libcurl needs to write data during sending
1597 * @param stream pointer where to write data
1598 * @param size size of an individual element
1599 * @param nmemb count of elements that can be written to the buffer
1600 * @param ptr destination pointer, passed to the libcurl handle
1601 * @return bytes read from stream
1602 */
1603 static size_t curl_receive_cb( void *stream, size_t size, size_t nmemb, void *ptr)
1604 {
1605   struct Session * ps = ptr;
1606
1607   if (ps->peercontext->delay.value > 0)
1608   {
1609 #if DEBUG_HTTP
1610           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: no inbound bandwidth available! Next read was delayed for  %llu ms\n", ps, ps->peercontext->delay.value);
1611 #endif
1612           return (0);
1613   }
1614
1615 #if DEBUG_CONNECTIONS
1616   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: %u bytes received\n",ps, size*nmemb);
1617 #endif
1618   GNUNET_SERVER_mst_receive(ps->msgtok, ps, stream, size*nmemb, GNUNET_NO, GNUNET_NO);
1619   return (size * nmemb);
1620
1621 }
1622
1623 static void curl_handle_finished (struct Plugin *plugin)
1624 {
1625         struct Session *ps = NULL;
1626         struct HTTP_PeerContext *pc = NULL;
1627         struct CURLMsg *msg;
1628         struct HTTP_Message * cur_msg = NULL;
1629
1630         int msgs_in_queue;
1631         char * tmp;
1632         long http_result;
1633
1634         do
1635           {
1636                 msg = curl_multi_info_read (plugin->multi_handle, &msgs_in_queue);
1637                 if ((msgs_in_queue == 0) || (msg == NULL))
1638                   break;
1639                 /* get session for affected curl handle */
1640                 GNUNET_assert ( msg->easy_handle != NULL );
1641                 curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, &tmp);
1642                 ps = (struct Session *) tmp;
1643                 GNUNET_assert ( ps != NULL );
1644                 pc = ps->peercontext;
1645                 GNUNET_assert ( pc != NULL );
1646                 switch (msg->msg)
1647                   {
1648
1649                   case CURLMSG_DONE:
1650                         if ( (msg->data.result != CURLE_OK) &&
1651                                  (msg->data.result != CURLE_GOT_NOTHING) )
1652                         {
1653                           /* sending msg failed*/
1654                           if (msg->easy_handle == ps->send_endpoint)
1655                           {
1656         #if DEBUG_CONNECTIONS
1657                                 GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1658                                                    _("Connection %X: HTTP PUT to peer `%s' (`%s') failed: `%s' `%s'\n"),
1659                                                    ps,
1660                                                    GNUNET_i2s(&pc->identity),
1661                                                    http_plugin_address_to_string(NULL, ps->addr, ps->addrlen),
1662                                                    "curl_multi_perform",
1663                                                    curl_easy_strerror (msg->data.result));
1664         #endif
1665                                 ps->send_connected = GNUNET_NO;
1666                                 ps->send_active = GNUNET_NO;
1667                                 curl_multi_remove_handle(plugin->multi_handle,ps->send_endpoint);
1668                                 //curl_easy_cleanup(ps->send_endpoint);
1669                                 //ps->send_endpoint=NULL;
1670                                 while (ps->pending_msgs_tail != NULL)
1671                                 {
1672                                         cur_msg = ps->pending_msgs_tail;
1673                                         if ( NULL != cur_msg->transmit_cont)
1674                                           cur_msg->transmit_cont (cur_msg->transmit_cont_cls,&pc->identity,GNUNET_SYSERR);
1675                                         ps->queue_length_cur -= cur_msg->size;
1676                                         remove_http_message(ps,cur_msg);
1677                                 }
1678                           }
1679                           /* GET connection failed */
1680                           if (msg->easy_handle == ps->recv_endpoint)
1681                           {
1682         #if DEBUG_CONNECTIONS
1683                                 GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1684                                          _("Connection %X: HTTP GET to peer `%s' (`%s') failed: `%s' `%s'\n"),
1685                                          ps,
1686                                          GNUNET_i2s(&pc->identity),
1687                                          http_plugin_address_to_string(NULL, ps->addr, ps->addrlen),
1688                                          "curl_multi_perform",
1689                                          curl_easy_strerror (msg->data.result));
1690         #endif
1691                                 ps->recv_connected = GNUNET_NO;
1692                                 ps->recv_active = GNUNET_NO;
1693                                 curl_multi_remove_handle(plugin->multi_handle,ps->recv_endpoint);
1694                                 //curl_easy_cleanup(ps->recv_endpoint);
1695                                 //ps->recv_endpoint=NULL;
1696                           }
1697                         }
1698                         else
1699                         {
1700                           if (msg->easy_handle == ps->send_endpoint)
1701                           {
1702                                 GNUNET_assert (CURLE_OK == curl_easy_getinfo(msg->easy_handle, CURLINFO_RESPONSE_CODE, &http_result));
1703         #if DEBUG_CONNECTIONS
1704                                 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1705                                                         "Connection %X: HTTP PUT connection to peer `%s' (`%s') was closed with HTTP code %u\n",
1706                                                          ps,
1707                                                          GNUNET_i2s(&pc->identity),
1708                                                          http_plugin_address_to_string(NULL, ps->addr, ps->addrlen),
1709                                                          http_result);
1710         #endif
1711                                 /* Calling transmit continuation  */
1712                                 while (ps->pending_msgs_tail != NULL)
1713                                 {
1714                                         cur_msg = ps->pending_msgs_tail;
1715                                         if ( NULL != cur_msg->transmit_cont)
1716                                         {
1717                                                   /* HTTP 1xx : Last message before here was informational */
1718                                                   if ((http_result >=100) && (http_result < 200))
1719                                                         cur_msg->transmit_cont (cur_msg->transmit_cont_cls,&pc->identity,GNUNET_OK);
1720                                                   /* HTTP 2xx: successful operations */
1721                                                   if ((http_result >=200) && (http_result < 300))
1722                                                         cur_msg->transmit_cont (cur_msg->transmit_cont_cls,&pc->identity,GNUNET_OK);
1723                                                   /* HTTP 3xx..5xx: error */
1724                                                   if ((http_result >=300) && (http_result < 600))
1725                                                         cur_msg->transmit_cont (cur_msg->transmit_cont_cls,&pc->identity,GNUNET_SYSERR);
1726                                         }
1727                                         ps->queue_length_cur -= cur_msg->size;
1728                                         remove_http_message(ps,cur_msg);
1729                                 }
1730
1731                                 ps->send_connected = GNUNET_NO;
1732                                 ps->send_active = GNUNET_NO;
1733                                 curl_multi_remove_handle(plugin->multi_handle,ps->send_endpoint);
1734                                 //curl_easy_cleanup(ps->send_endpoint);
1735                                 //ps->send_endpoint =NULL;
1736                           }
1737                           if (msg->easy_handle == ps->recv_endpoint)
1738                           {
1739         #if DEBUG_CONNECTIONS
1740                                 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1741                                                         "Connection %X: HTTP GET connection to peer `%s' (`%s') was closed with HTTP code %u\n",
1742                                                          ps,
1743                                                          GNUNET_i2s(&pc->identity),
1744                                                          http_plugin_address_to_string(NULL, ps->addr, ps->addrlen),
1745                                                          http_result);
1746         #endif
1747                                 ps->recv_connected = GNUNET_NO;
1748                                 ps->recv_active = GNUNET_NO;
1749                                 curl_multi_remove_handle(plugin->multi_handle,ps->recv_endpoint);
1750                                 //curl_easy_cleanup(ps->recv_endpoint);
1751                                 //ps->recv_endpoint=NULL;
1752                           }
1753                         }
1754                         if ((ps->recv_connected == GNUNET_NO) && (ps->send_connected == GNUNET_NO))
1755                           remove_session (pc, ps, GNUNET_YES, GNUNET_SYSERR);
1756                         break;
1757                   default:
1758                         break;
1759                   }
1760           }
1761         while ( (msgs_in_queue > 0) );
1762 }
1763
1764
1765 /**
1766  * Task performing curl operations
1767  * @param cls plugin as closure
1768  * @param tc gnunet scheduler task context
1769  */
1770 static void curl_perform (void *cls,
1771              const struct GNUNET_SCHEDULER_TaskContext *tc)
1772 {
1773   struct Plugin *plugin = cls;
1774   static unsigned int handles_last_run;
1775   int running;
1776   CURLMcode mret;
1777
1778   GNUNET_assert(cls !=NULL);
1779
1780   plugin->http_curl_task = GNUNET_SCHEDULER_NO_TASK;
1781   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1782     return;
1783   do
1784     {
1785       running = 0;
1786       mret = curl_multi_perform (plugin->multi_handle, &running);
1787       if ((running < handles_last_run) && (running>0))
1788           curl_handle_finished(plugin);
1789       handles_last_run = running;
1790     }
1791   while (mret == CURLM_CALL_MULTI_PERFORM);
1792   curl_schedule(plugin);
1793 }
1794
1795
1796 /**
1797  * Function setting up file descriptors and scheduling task to run
1798  *
1799  * @param plugin plugin as closure
1800  * @return GNUNET_SYSERR for hard failure, GNUNET_OK for ok
1801  */
1802 static int curl_schedule(struct Plugin *plugin)
1803 {
1804   fd_set rs;
1805   fd_set ws;
1806   fd_set es;
1807   int max;
1808   struct GNUNET_NETWORK_FDSet *grs;
1809   struct GNUNET_NETWORK_FDSet *gws;
1810   long to;
1811   CURLMcode mret;
1812
1813   /* Cancel previous scheduled task */
1814   if (plugin->http_curl_task !=  GNUNET_SCHEDULER_NO_TASK)
1815   {
1816           GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_curl_task);
1817           plugin->http_curl_task = GNUNET_SCHEDULER_NO_TASK;
1818   }
1819
1820   max = -1;
1821   FD_ZERO (&rs);
1822   FD_ZERO (&ws);
1823   FD_ZERO (&es);
1824   mret = curl_multi_fdset (plugin->multi_handle, &rs, &ws, &es, &max);
1825   if (mret != CURLM_OK)
1826     {
1827       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1828                   _("%s failed at %s:%d: `%s'\n"),
1829                   "curl_multi_fdset", __FILE__, __LINE__,
1830                   curl_multi_strerror (mret));
1831       return GNUNET_SYSERR;
1832     }
1833   mret = curl_multi_timeout (plugin->multi_handle, &to);
1834   if (mret != CURLM_OK)
1835     {
1836       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1837                   _("%s failed at %s:%d: `%s'\n"),
1838                   "curl_multi_timeout", __FILE__, __LINE__,
1839                   curl_multi_strerror (mret));
1840       return GNUNET_SYSERR;
1841     }
1842
1843   grs = GNUNET_NETWORK_fdset_create ();
1844   gws = GNUNET_NETWORK_fdset_create ();
1845   GNUNET_NETWORK_fdset_copy_native (grs, &rs, max + 1);
1846   GNUNET_NETWORK_fdset_copy_native (gws, &ws, max + 1);
1847   plugin->http_curl_task = GNUNET_SCHEDULER_add_select (plugin->env->sched,
1848                                    GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1849                                    GNUNET_SCHEDULER_NO_TASK,
1850                                                                     (to == -1) ? GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5) : GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, to),
1851                                    grs,
1852                                    gws,
1853                                    &curl_perform,
1854                                    plugin);
1855   GNUNET_NETWORK_fdset_destroy (gws);
1856   GNUNET_NETWORK_fdset_destroy (grs);
1857   return GNUNET_OK;
1858 }
1859
1860 /**
1861  * Function to log curl debug messages with GNUNET_log
1862  * @param curl handle
1863  * @param type curl_infotype
1864  * @param data data
1865  * @param size size
1866  * @param cls  closure
1867  * @return 0
1868  */
1869 int curl_logger (CURL * curl, curl_infotype type , char * data, size_t size , void * cls)
1870 {
1871
1872         if (type == CURLINFO_TEXT)
1873         {
1874                 char text[size+2];
1875                 memcpy(text,data,size);
1876                 if (text[size-1] == '\n')
1877                         text[size] = '\0';
1878                 else
1879                 {
1880                         text[size] = '\n';
1881                         text[size+1] = '\0';
1882                 }
1883                 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"CURL: Connection %X - %s", cls, text);
1884         }
1885         return 0;
1886 }
1887
1888 /**
1889  * Function setting up curl handle and selecting message to send
1890  *
1891  * @param plugin plugin
1892  * @param ps session
1893  * @return GNUNET_SYSERR on failure, GNUNET_NO if connecting, GNUNET_YES if ok
1894  */
1895 static int send_check_connections (struct Plugin *plugin, struct Session *ps)
1896 {
1897   CURLMcode mret;
1898   struct HTTP_Message * msg;
1899
1900   struct GNUNET_TIME_Relative timeout = GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT;
1901
1902   if (ps->direction == OUTBOUND)
1903   {
1904     /* RECV DIRECTION */
1905     /* Check if session is connected to receive data, otherwise connect to peer */
1906     if (ps->recv_connected == GNUNET_NO)
1907     {
1908         int fresh = GNUNET_NO;
1909         if (ps->recv_endpoint == NULL)
1910         {
1911             fresh = GNUNET_YES;
1912                 ps->recv_endpoint = curl_easy_init();
1913         }
1914 #if DEBUG_CURL
1915         curl_easy_setopt(ps->recv_endpoint, CURLOPT_VERBOSE, 1L);
1916         curl_easy_setopt(ps->recv_endpoint, CURLOPT_DEBUGFUNCTION , &curl_logger);
1917         curl_easy_setopt(ps->recv_endpoint, CURLOPT_DEBUGDATA , ps->recv_endpoint);
1918 #endif
1919 #if BUILD_HTTPS
1920         curl_easy_setopt (ps->recv_endpoint, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
1921                 curl_easy_setopt(ps->recv_endpoint, CURLOPT_SSL_VERIFYPEER, 0);
1922                 curl_easy_setopt(ps->recv_endpoint, CURLOPT_SSL_VERIFYHOST, 0);
1923 #endif
1924         curl_easy_setopt(ps->recv_endpoint, CURLOPT_URL, ps->url);
1925         curl_easy_setopt(ps->recv_endpoint, CURLOPT_HEADERFUNCTION, &curl_get_header_cb);
1926         curl_easy_setopt(ps->recv_endpoint, CURLOPT_WRITEHEADER, ps);
1927         curl_easy_setopt(ps->recv_endpoint, CURLOPT_READFUNCTION, curl_send_cb);
1928         curl_easy_setopt(ps->recv_endpoint, CURLOPT_READDATA, ps);
1929         curl_easy_setopt(ps->recv_endpoint, CURLOPT_WRITEFUNCTION, curl_receive_cb);
1930         curl_easy_setopt(ps->recv_endpoint, CURLOPT_WRITEDATA, ps);
1931         curl_easy_setopt(ps->recv_endpoint, CURLOPT_TIMEOUT, (long) timeout.value);
1932         curl_easy_setopt(ps->recv_endpoint, CURLOPT_PRIVATE, ps);
1933         curl_easy_setopt(ps->recv_endpoint, CURLOPT_CONNECTTIMEOUT, HTTP_CONNECT_TIMEOUT);
1934         curl_easy_setopt(ps->recv_endpoint, CURLOPT_BUFFERSIZE, 2*GNUNET_SERVER_MAX_MESSAGE_SIZE);
1935 #if CURL_TCP_NODELAY
1936         curl_easy_setopt(ps->recv_endpoint, CURLOPT_TCP_NODELAY, 1);
1937 #endif
1938
1939         if (fresh==GNUNET_YES)
1940         {
1941                         mret = curl_multi_add_handle(plugin->multi_handle, ps->recv_endpoint);
1942                         if (mret != CURLM_OK)
1943                         {
1944                           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1945                                                   _("Connection: %X: %s failed at %s:%d: `%s'\n"),
1946                                                   ps,
1947                                                   "curl_multi_add_handle", __FILE__, __LINE__,
1948                                                   curl_multi_strerror (mret));
1949                           return GNUNET_SYSERR;
1950                         }
1951         }
1952                 if (plugin->http_curl_task !=  GNUNET_SCHEDULER_NO_TASK)
1953                 {
1954                   GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_curl_task);
1955                   plugin->http_curl_task = GNUNET_SCHEDULER_NO_TASK;
1956                 }
1957                 plugin->http_curl_task = GNUNET_SCHEDULER_add_now (plugin->env->sched, &curl_perform, plugin);
1958     }
1959
1960     /* waiting for receive direction */
1961     if (ps->recv_connected==GNUNET_NO)
1962       return GNUNET_NO;
1963
1964     /* SEND DIRECTION */
1965     /* Check if session is connected to send data, otherwise connect to peer */
1966     if ((ps->send_connected == GNUNET_YES) && (ps->send_endpoint!= NULL))
1967     {
1968       if (ps->send_active == GNUNET_YES)
1969       {
1970 #if DEBUG_CONNECTIONS
1971         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: outbound active, enqueueing message\n",ps);
1972 #endif
1973         return GNUNET_YES;
1974       }
1975       if (ps->send_active == GNUNET_NO)
1976       {
1977 #if DEBUG_CONNECTIONS
1978         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: outbound paused, unpausing existing connection and enqueueing message\n",ps);
1979 #endif
1980         if (CURLE_OK == curl_easy_pause(ps->send_endpoint,CURLPAUSE_CONT))
1981         {
1982                         ps->send_active=GNUNET_YES;
1983                         if (plugin->http_curl_task !=  GNUNET_SCHEDULER_NO_TASK)
1984                         {
1985                           GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_curl_task);
1986                           plugin->http_curl_task = GNUNET_SCHEDULER_NO_TASK;
1987                         }
1988                         plugin->http_curl_task = GNUNET_SCHEDULER_add_now (plugin->env->sched, &curl_perform, plugin);
1989                         return GNUNET_YES;
1990         }
1991         else
1992                 return GNUNET_SYSERR;
1993       }
1994     }
1995     /* not connected, initiate connection */
1996     if (ps->send_connected==GNUNET_NO)
1997     {
1998         int fresh = GNUNET_NO;
1999         if (NULL == ps->send_endpoint)
2000         {
2001                 ps->send_endpoint = curl_easy_init();
2002                 fresh = GNUNET_YES;
2003         }
2004                 GNUNET_assert (ps->send_endpoint != NULL);
2005                 GNUNET_assert (NULL != ps->pending_msgs_tail);
2006 #if DEBUG_CONNECTIONS
2007                 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: outbound not connected, initiating connection\n",ps);
2008 #endif
2009                 ps->send_active = GNUNET_NO;
2010                 msg = ps->pending_msgs_tail;
2011
2012 #if DEBUG_CURL
2013                 curl_easy_setopt(ps->send_endpoint, CURLOPT_VERBOSE, 1L);
2014         curl_easy_setopt(ps->send_endpoint, CURLOPT_DEBUGFUNCTION , &curl_logger);
2015         curl_easy_setopt(ps->send_endpoint, CURLOPT_DEBUGDATA , ps->send_endpoint);
2016 #endif
2017 #if BUILD_HTTPS
2018         curl_easy_setopt (ps->send_endpoint, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
2019                 curl_easy_setopt(ps->send_endpoint, CURLOPT_SSL_VERIFYPEER, 0);
2020                 curl_easy_setopt(ps->send_endpoint, CURLOPT_SSL_VERIFYHOST, 0);
2021 #endif
2022                 curl_easy_setopt(ps->send_endpoint, CURLOPT_URL, ps->url);
2023                 curl_easy_setopt(ps->send_endpoint, CURLOPT_PUT, 1L);
2024                 curl_easy_setopt(ps->send_endpoint, CURLOPT_HEADERFUNCTION, &curl_put_header_cb);
2025                 curl_easy_setopt(ps->send_endpoint, CURLOPT_WRITEHEADER, ps);
2026                 curl_easy_setopt(ps->send_endpoint, CURLOPT_READFUNCTION, curl_send_cb);
2027                 curl_easy_setopt(ps->send_endpoint, CURLOPT_READDATA, ps);
2028                 curl_easy_setopt(ps->send_endpoint, CURLOPT_WRITEFUNCTION, curl_receive_cb);
2029                 curl_easy_setopt(ps->send_endpoint, CURLOPT_READDATA, ps);
2030                 curl_easy_setopt(ps->send_endpoint, CURLOPT_TIMEOUT, (long) timeout.value);
2031                 curl_easy_setopt(ps->send_endpoint, CURLOPT_PRIVATE, ps);
2032                 curl_easy_setopt(ps->send_endpoint, CURLOPT_CONNECTTIMEOUT, HTTP_CONNECT_TIMEOUT);
2033                 curl_easy_setopt(ps->send_endpoint, CURLOPT_BUFFERSIZE, 2 * GNUNET_SERVER_MAX_MESSAGE_SIZE);
2034 #if CURL_TCP_NODELAY
2035                 curl_easy_setopt(ps->send_endpoint, CURLOPT_TCP_NODELAY, 1);
2036 #endif
2037
2038                 if (fresh==GNUNET_YES)
2039                 {
2040                         mret = curl_multi_add_handle(plugin->multi_handle, ps->send_endpoint);
2041                         if (mret != CURLM_OK)
2042                         {
2043                           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2044                                                   _("Connection: %X: %s failed at %s:%d: `%s'\n"),
2045                                                   ps,
2046                                                   "curl_multi_add_handle", __FILE__, __LINE__,
2047                                                   curl_multi_strerror (mret));
2048                           return GNUNET_SYSERR;
2049                         }
2050                 }
2051     }
2052         if (plugin->http_curl_task !=  GNUNET_SCHEDULER_NO_TASK)
2053         {
2054           GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_curl_task);
2055           plugin->http_curl_task = GNUNET_SCHEDULER_NO_TASK;
2056         }
2057         plugin->http_curl_task = GNUNET_SCHEDULER_add_now (plugin->env->sched, &curl_perform, plugin);
2058     return GNUNET_YES;
2059   }
2060   if (ps->direction == INBOUND)
2061   {
2062     GNUNET_assert (NULL != ps->pending_msgs_tail);
2063     if ((ps->recv_connected==GNUNET_YES) && (ps->send_connected==GNUNET_YES) &&
2064         (ps->recv_force_disconnect==GNUNET_NO) && (ps->recv_force_disconnect==GNUNET_NO))
2065         return GNUNET_YES;
2066   }
2067   return GNUNET_SYSERR;
2068 }
2069
2070 /**
2071  * select best session to transmit data to peer
2072  *
2073  * @param pc peer context of target peer
2074  * @param addr address of target peer
2075  * @param addrlen address length
2076  * @param force_address does transport service enforce address?
2077  * @param session session passed by transport service
2078  * @return selected session
2079  *
2080  */
2081 static struct Session * send_select_session (struct HTTP_PeerContext *pc, const void * addr, size_t addrlen, int force_address, struct Session * session)
2082 {
2083         struct Session * tmp = NULL;
2084         int addr_given = GNUNET_NO;
2085
2086         if ((addr!=NULL) && (addrlen>0))
2087                 addr_given = GNUNET_YES;
2088
2089         if (force_address == GNUNET_YES)
2090         {
2091                 /* check session given as argument */
2092                 if ((session != NULL) && (addr_given == GNUNET_YES))
2093                 {
2094                       if (0 == memcmp(session->addr, addr, addrlen))
2095                       {
2096                         /* connection can not be used, since it is disconnected */
2097                         if ((session->recv_force_disconnect==GNUNET_NO) && (session->send_force_disconnect==GNUNET_NO))
2098                         {
2099 #if DEBUG_SESSION_SELECTION
2100                                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Session %X selected: Using session passed by transport to send to forced address \n", session);
2101 #endif
2102                                 return session;
2103                         }
2104                       }
2105                 }
2106                 /* check last session used */
2107                 if ((pc->last_session != NULL)&& (addr_given == GNUNET_YES))
2108                 {
2109                       if (0 == memcmp(pc->last_session->addr, addr, addrlen))
2110                       {
2111                         /* connection can not be used, since it is disconnected */
2112                         if ((pc->last_session->recv_force_disconnect==GNUNET_NO) && (pc->last_session->send_force_disconnect==GNUNET_NO))
2113                         {
2114 #if DEBUG_SESSION_SELECTION
2115                                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Session %X selected: Using last session used to send to forced address \n", pc->last_session);
2116 #endif
2117                                 return pc->last_session;
2118                         }
2119                       }
2120                 }
2121                 /* find session in existing sessions */
2122                 tmp = pc->head;
2123                 while ((tmp!=NULL) && (addr_given == GNUNET_YES))
2124                 {
2125
2126                           if (0 == memcmp(tmp->addr, addr, addrlen))
2127                       {
2128                         /* connection can not be used, since it is disconnected */
2129                         if ((tmp->recv_force_disconnect==GNUNET_NO) && (tmp->send_force_disconnect==GNUNET_NO))
2130                         {
2131 #if DEBUG_SESSION_SELECTION
2132                                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Session %X selected: Using existing session to send to forced address \n", session);
2133 #endif
2134                                   return session;
2135                         }
2136
2137                       }
2138                           tmp=tmp->next;
2139                 }
2140                 /* no session to use */
2141                 return NULL;
2142         }
2143         if ((force_address == GNUNET_NO) || (force_address == GNUNET_SYSERR))
2144         {
2145                 /* check session given as argument */
2146                 if (session != NULL)
2147                 {
2148                         /* connection can not be used, since it is disconnected */
2149                         if ((session->recv_force_disconnect==GNUNET_NO) && (session->send_force_disconnect==GNUNET_NO))
2150                         {
2151 #if DEBUG_SESSION_SELECTION
2152                                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Session %X selected: Using session passed by transport to send not-forced address \n", session);
2153 #endif
2154                                   return session;
2155                         }
2156
2157                 }
2158                 /* check last session used */
2159                 if (pc->last_session != NULL)
2160                 {
2161                         /* connection can not be used, since it is disconnected */
2162                         if ((pc->last_session->recv_force_disconnect==GNUNET_NO) && (pc->last_session->send_force_disconnect==GNUNET_NO))
2163                         {
2164 #if DEBUG_SESSION_SELECTION
2165                                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Session %X selected: Using last session to send to not-forced address \n", pc->last_session);
2166 #endif
2167                                 return pc->last_session;
2168                         }
2169                 }
2170                 /* find session in existing sessions */
2171                 tmp = pc->head;
2172                 while (tmp!=NULL)
2173                 {
2174                         /* connection can not be used, since it is disconnected */
2175                         if ((tmp->recv_force_disconnect==GNUNET_NO) && (tmp->send_force_disconnect==GNUNET_NO))
2176                         {
2177 #if DEBUG_SESSION_SELECTION
2178                                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Session %X selected: Using existing session to send to not-forced address \n", tmp);
2179 #endif
2180                                 return tmp;
2181                         }
2182                         tmp=tmp->next;
2183                 }
2184                 return NULL;
2185         }
2186         return NULL;
2187 }
2188
2189 /**
2190  * Function that can be used by the transport service to transmit
2191  * a message using the plugin.   Note that in the case of a
2192  * peer disconnecting, the continuation MUST be called
2193  * prior to the disconnect notification itself.  This function
2194  * will be called with this peer's HELLO message to initiate
2195  * a fresh connection to another peer.
2196  *
2197  * @param cls closure
2198  * @param target who should receive this message
2199  * @param msgbuf the message to transmit
2200  * @param msgbuf_size number of bytes in 'msgbuf'
2201  * @param priority how important is the message (most plugins will
2202  *                 ignore message priority and just FIFO)
2203  * @param to how long to wait at most for the transmission (does not
2204  *                require plugins to discard the message after the timeout,
2205  *                just advisory for the desired delay; most plugins will ignore
2206  *                this as well)
2207  * @param session which session must be used (or NULL for "any")
2208  * @param addr the address to use (can be NULL if the plugin
2209  *                is "on its own" (i.e. re-use existing TCP connection))
2210  * @param addrlen length of the address in bytes
2211  * @param force_address GNUNET_YES if the plugin MUST use the given address,
2212  *                GNUNET_NO means the plugin may use any other address and
2213  *                GNUNET_SYSERR means that only reliable existing
2214  *                bi-directional connections should be used (regardless
2215  *                of address)
2216  * @param cont continuation to call once the message has
2217  *        been transmitted (or if the transport is ready
2218  *        for the next transmission call; or if the
2219  *        peer disconnected...); can be NULL
2220  * @param cont_cls closure for cont
2221  * @return number of bytes used (on the physical network, with overheads);
2222  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
2223  *         and does NOT mean that the message was not transmitted (DV)
2224  */
2225 static ssize_t
2226 http_plugin_send (void *cls,
2227                   const struct GNUNET_PeerIdentity *target,
2228                   const char *msgbuf,
2229                   size_t msgbuf_size,
2230                   unsigned int priority,
2231                   struct GNUNET_TIME_Relative to,
2232                   struct Session *session,
2233                   const void *addr,
2234                   size_t addrlen,
2235                   int force_address,
2236                   GNUNET_TRANSPORT_TransmitContinuation cont,
2237                   void *cont_cls)
2238 {
2239   struct Plugin *plugin = cls;
2240   struct HTTP_Message *msg;
2241   struct HTTP_PeerContext * pc;
2242   struct Session * ps = NULL;
2243
2244   GNUNET_assert(cls !=NULL);
2245
2246 #if DEBUG_HTTP
2247   char * force;
2248   if (force_address == GNUNET_YES)
2249           GNUNET_asprintf(&force, "forced addr.");
2250   if (force_address == GNUNET_NO)
2251           GNUNET_asprintf(&force, "any addr.");
2252   if (force_address == GNUNET_SYSERR)
2253           GNUNET_asprintf(&force,"reliable bi-direc. address addr.");
2254
2255   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Transport tells me to send %u bytes to `%s' using %s (%s) and session: %X\n",
2256                                       msgbuf_size,
2257                                       GNUNET_i2s(target),
2258                                       force,
2259                                       http_plugin_address_to_string(NULL, addr, addrlen),
2260                                       session);
2261
2262   GNUNET_free(force);
2263 #endif
2264
2265   pc = GNUNET_CONTAINER_multihashmap_get (plugin->peers, &target->hashPubKey);
2266   /* Peer unknown */
2267   if (pc==NULL)
2268   {
2269     pc = GNUNET_malloc(sizeof (struct HTTP_PeerContext));
2270     pc->plugin = plugin;
2271     pc->session_id_counter=1;
2272     pc->last_session = NULL;
2273     memcpy(&pc->identity, target, sizeof(struct GNUNET_PeerIdentity));
2274     GNUNET_CONTAINER_multihashmap_put(plugin->peers, &pc->identity.hashPubKey, pc, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2275     GNUNET_STATISTICS_update (plugin->env->stats,
2276                             gettext_noop ("# HTTP peers active"),
2277                             1,
2278                             GNUNET_NO);
2279   }
2280
2281   ps = send_select_session (pc, addr, addrlen, force_address, session);
2282
2283   /* session not existing, but address forced -> creating new session */
2284   if (ps==NULL)
2285   {
2286         if ((addr!=NULL) && (addrlen!=0))
2287         {
2288       ps = GNUNET_malloc(sizeof (struct Session));
2289 #if DEBUG_SESSION_SELECTION
2290       if (force_address == GNUNET_YES)
2291          GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"No existing connection & forced address: creating new session %X to peer %s\n", ps, GNUNET_i2s(target));
2292       if (force_address != GNUNET_YES)
2293          GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"No existing connection: creating new session %X to peer %s\n", ps, GNUNET_i2s(target));
2294 #endif
2295       if ((addrlen!=0) && (addr!=NULL))
2296       {
2297          ps->addr = GNUNET_malloc(addrlen);
2298          memcpy(ps->addr,addr,addrlen);
2299          ps->addrlen = addrlen;
2300       }
2301           else
2302           {
2303                 ps->addr = NULL;
2304                 ps->addrlen = 0;
2305           }
2306           ps->direction=OUTBOUND;
2307           ps->recv_connected = GNUNET_NO;
2308           ps->recv_force_disconnect = GNUNET_NO;
2309           ps->send_connected = GNUNET_NO;
2310           ps->send_force_disconnect = GNUNET_NO;
2311           ps->pending_msgs_head = NULL;
2312           ps->pending_msgs_tail = NULL;
2313           ps->peercontext=pc;
2314           ps->session_id = pc->session_id_counter;
2315           ps->queue_length_cur = 0;
2316           ps->queue_length_max = GNUNET_SERVER_MAX_MESSAGE_SIZE;
2317           pc->session_id_counter++;
2318           ps->url = create_url (plugin, ps->addr, ps->addrlen, ps->session_id);
2319           if (ps->msgtok == NULL)
2320                         ps->msgtok = GNUNET_SERVER_mst_create (&curl_receive_mst_cb, ps);
2321           GNUNET_CONTAINER_DLL_insert(pc->head,pc->tail,ps);
2322           GNUNET_STATISTICS_update (plugin->env->stats,
2323                                                                 gettext_noop ("# HTTP outbound sessions for peers active"),
2324                                                                 1,
2325                                                                 GNUNET_NO);
2326         }
2327         else
2328         {
2329 #if DEBUG_HTTP
2330                 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"No existing session found & and no address given: no way to send this message to peer `%s'!\n", GNUNET_i2s(target));
2331 #endif
2332                 return GNUNET_SYSERR;
2333     }
2334   }
2335
2336   if (msgbuf_size >= (ps->queue_length_max - ps->queue_length_cur))
2337   {
2338         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Queue %X full: %u bytes in queue available, message with %u is too big\n", ps, (ps->queue_length_max - ps->queue_length_cur), msgbuf_size);
2339         //return GNUNET_SYSERR;
2340   }
2341
2342         /* create msg */
2343         msg = GNUNET_malloc (sizeof (struct HTTP_Message) + msgbuf_size);
2344         msg->next = NULL;
2345         msg->size = msgbuf_size;
2346         msg->pos = 0;
2347         msg->buf = (char *) &msg[1];
2348         msg->transmit_cont = cont;
2349         msg->transmit_cont_cls = cont_cls;
2350         memcpy (msg->buf,msgbuf, msgbuf_size);
2351
2352         GNUNET_CONTAINER_DLL_insert(ps->pending_msgs_head,ps->pending_msgs_tail,msg);
2353         ps->queue_length_cur += msgbuf_size;
2354
2355         if (send_check_connections (plugin, ps) == GNUNET_SYSERR)
2356           return GNUNET_SYSERR;
2357           if (force_address != GNUNET_YES)
2358                   pc->last_session = ps;
2359
2360           if (pc->last_session==NULL)
2361                   pc->last_session = ps;
2362           return msg->size;
2363 }
2364
2365
2366
2367 /**
2368  * Function that can be used to force the plugin to disconnect
2369  * from the given peer and cancel all previous transmissions
2370  * (and their continuationc).
2371  *
2372  * @param cls closure
2373  * @param target peer from which to disconnect
2374  */
2375 static void
2376 http_plugin_disconnect (void *cls,
2377                             const struct GNUNET_PeerIdentity *target)
2378 {
2379
2380
2381   struct Plugin *plugin = cls;
2382   struct HTTP_PeerContext *pc = NULL;
2383   struct Session *ps = NULL;
2384   //struct Session *tmp = NULL;
2385
2386   pc = GNUNET_CONTAINER_multihashmap_get (plugin->peers, &target->hashPubKey);
2387   if (pc==NULL)
2388     return;
2389   ps = pc->head;
2390
2391   while (ps!=NULL)
2392   {
2393     /* Telling transport that session is getting disconnected */
2394     plugin->env->session_end(plugin, target, ps);
2395     if (ps->direction==OUTBOUND)
2396     {
2397       if (ps->send_endpoint!=NULL)
2398       {
2399         //GNUNET_assert(CURLM_OK == curl_multi_remove_handle(plugin->multi_handle,ps->send_endpoint));
2400         //curl_easy_cleanup(ps->send_endpoint);
2401         //ps->send_endpoint=NULL;
2402         ps->send_force_disconnect = GNUNET_YES;
2403       }
2404       if (ps->recv_endpoint!=NULL)
2405       {
2406        //GNUNET_assert(CURLM_OK == curl_multi_remove_handle(plugin->multi_handle,ps->recv_endpoint));
2407        //curl_easy_cleanup(ps->recv_endpoint);
2408        //ps->recv_endpoint=NULL;
2409        ps->recv_force_disconnect = GNUNET_YES;
2410       }
2411     }
2412
2413     if (ps->direction==INBOUND)
2414     {
2415       ps->recv_force_disconnect = GNUNET_YES;
2416       ps->send_force_disconnect = GNUNET_YES;
2417     }
2418
2419     while (ps->pending_msgs_head!=NULL)
2420     {
2421       remove_http_message(ps, ps->pending_msgs_head);
2422     }
2423     ps->recv_active = GNUNET_NO;
2424     ps->send_active = GNUNET_NO;
2425     ps=ps->next;
2426   }
2427 }
2428
2429
2430 /**
2431  * Convert the transports address to a nice, human-readable
2432  * format.
2433  *
2434  * @param cls closure
2435  * @param type name of the transport that generated the address
2436  * @param addr one of the addresses of the host, NULL for the last address
2437  *        the specific address format depends on the transport
2438  * @param addrlen length of the address
2439  * @param numeric should (IP) addresses be displayed in numeric form?
2440  * @param timeout after how long should we give up?
2441  * @param asc function to call on each string
2442  * @param asc_cls closure for asc
2443  */
2444 static void
2445 http_plugin_address_pretty_printer (void *cls,
2446                                         const char *type,
2447                                         const void *addr,
2448                                         size_t addrlen,
2449                                         int numeric,
2450                                         struct GNUNET_TIME_Relative timeout,
2451                                         GNUNET_TRANSPORT_AddressStringCallback
2452                                         asc, void *asc_cls)
2453 {
2454   const struct IPv4HttpAddress *t4;
2455   const struct IPv6HttpAddress *t6;
2456   struct sockaddr_in a4;
2457   struct sockaddr_in6 a6;
2458   char * address;
2459   char * ret;
2460   unsigned int port;
2461   unsigned int res;
2462
2463   GNUNET_assert(cls !=NULL);
2464   if (addrlen == sizeof (struct IPv6HttpAddress))
2465   {
2466     address = GNUNET_malloc (INET6_ADDRSTRLEN);
2467     t6 = addr;
2468     a6.sin6_addr = t6->ipv6_addr;
2469     inet_ntop(AF_INET6, &(a6.sin6_addr),address,INET6_ADDRSTRLEN);
2470     port = ntohs(t6->u6_port);
2471   }
2472   else if (addrlen == sizeof (struct IPv4HttpAddress))
2473   {
2474     address = GNUNET_malloc (INET_ADDRSTRLEN);
2475     t4 = addr;
2476     a4.sin_addr.s_addr =  t4->ipv4_addr;
2477     inet_ntop(AF_INET, &(a4.sin_addr),address,INET_ADDRSTRLEN);
2478     port = ntohs(t4->u_port);
2479   }
2480   else
2481   {
2482     /* invalid address */
2483     GNUNET_break_op (0);
2484     asc (asc_cls, NULL);
2485     return;
2486   }
2487   res = GNUNET_asprintf(&ret,"%s://%s:%u/", PROTOCOL_PREFIX, address, port);
2488   GNUNET_free (address);
2489   GNUNET_assert(res != 0);
2490   asc (asc_cls, ret);
2491   GNUNET_free_non_null (ret);
2492 }
2493
2494
2495
2496 /**
2497  * Another peer has suggested an address for this
2498  * peer and transport plugin.  Check that this could be a valid
2499  * address.  If so, consider adding it to the list
2500  * of addresses.
2501  *
2502  * @param cls closure
2503  * @param addr pointer to the address
2504  * @param addrlen length of addr
2505  * @return GNUNET_OK if this is a plausible address for this peer
2506  *         and transport
2507  */
2508 static int
2509 http_plugin_address_suggested (void *cls,
2510                                const void *addr, size_t addrlen)
2511 {
2512   struct Plugin *plugin = cls;
2513   struct IPv4HttpAddress *v4;
2514   struct IPv6HttpAddress *v6;
2515
2516   struct IPv4HttpAddress *tv4 = plugin->ipv4_addr_head;
2517   struct IPv6HttpAddress *tv6 = plugin->ipv6_addr_head;
2518
2519   GNUNET_assert(cls !=NULL);
2520   if ((addrlen != sizeof (struct IPv4HttpAddress)) &&
2521       (addrlen != sizeof (struct IPv6HttpAddress)))
2522     {
2523       return GNUNET_SYSERR;
2524     }
2525   if (addrlen == sizeof (struct IPv4HttpAddress))
2526     {
2527       v4 = (struct IPv4HttpAddress *) addr;
2528
2529       if (plugin->bind4_address!=NULL)
2530       {
2531           if (0 == memcmp (&plugin->bind4_address->sin_addr, &v4->ipv4_addr, sizeof(uint32_t)))
2532                   return GNUNET_OK;
2533           else
2534                   return GNUNET_SYSERR;
2535       }
2536       while (tv4!=NULL)
2537       {
2538           if (0==memcmp (&tv4->ipv4_addr, &v4->ipv4_addr, sizeof(uint32_t)))
2539                   break;
2540           tv4 = tv4->next;
2541       }
2542       if (tv4 != NULL)
2543         return GNUNET_OK;
2544           else
2545                   return GNUNET_SYSERR;
2546     }
2547   if (addrlen == sizeof (struct IPv6HttpAddress))
2548     {
2549       v6 = (struct IPv6HttpAddress *) addr;
2550
2551       if (plugin->bind6_address!=NULL)
2552       {
2553           if (0 == memcmp (&plugin->bind6_address->sin6_addr, &v6->ipv6_addr, sizeof(struct in6_addr)))
2554                   return GNUNET_OK;
2555           else
2556                   return GNUNET_SYSERR;
2557       }
2558
2559       while (tv6!=NULL)
2560       {
2561           if (0 == memcmp (&tv6->ipv6_addr, &v6->ipv6_addr, sizeof(struct in6_addr)))
2562                   break;
2563           tv6 = tv6->next;
2564       }
2565       if (tv6 !=NULL)
2566         return GNUNET_OK;
2567           else
2568                   return GNUNET_SYSERR;
2569     }
2570
2571   return GNUNET_SYSERR;
2572 }
2573
2574
2575 /**
2576  * Function called for a quick conversion of the binary address to
2577  * a numeric address.  Note that the caller must not free the
2578  * address and that the next call to this function is allowed
2579  * to override the address again.
2580  *
2581  * @param cls closure
2582  * @param addr binary address
2583  * @param addrlen length of the address
2584  * @return string representing the same address
2585  */
2586 static const char*
2587 http_plugin_address_to_string (void *cls,
2588                                    const void *addr,
2589                                    size_t addrlen)
2590 {
2591   const struct IPv4HttpAddress *t4;
2592   const struct IPv6HttpAddress *t6;
2593   struct sockaddr_in a4;
2594   struct sockaddr_in6 a6;
2595   char * address;
2596   char * ret;
2597   uint16_t port;
2598   unsigned int res;
2599
2600   if (addrlen == sizeof (struct IPv6HttpAddress))
2601     {
2602       address = GNUNET_malloc (INET6_ADDRSTRLEN);
2603       t6 = addr;
2604       a6.sin6_addr = t6->ipv6_addr;
2605       inet_ntop(AF_INET6, &(a6.sin6_addr),address,INET6_ADDRSTRLEN);
2606       port = ntohs(t6->u6_port);
2607     }
2608   else if (addrlen == sizeof (struct IPv4HttpAddress))
2609     {
2610       address = GNUNET_malloc (INET_ADDRSTRLEN);
2611       t4 = addr;
2612       a4.sin_addr.s_addr =  t4->ipv4_addr;
2613       inet_ntop(AF_INET, &(a4.sin_addr),address,INET_ADDRSTRLEN);
2614       port = ntohs(t4->u_port);
2615     }
2616   else
2617     {
2618       /* invalid address */
2619       return NULL;
2620     }
2621   res = GNUNET_asprintf(&ret,"%s:%u",address,port);
2622   GNUNET_free (address);
2623   GNUNET_assert(res != 0);
2624   return ret;
2625 }
2626
2627
2628 /**
2629  * Exit point from the plugin.
2630  */
2631 void *
2632 LIBGNUNET_PLUGIN_TRANSPORT_DONE (void *cls)
2633 {
2634   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2635   struct Plugin *plugin = api->cls;
2636   CURLMcode mret;
2637   struct IPv4HttpAddress * ipv4addr;
2638   struct IPv6HttpAddress * ipv6addr;
2639   GNUNET_assert(cls !=NULL);
2640
2641   if (plugin->http_server_daemon_v4 != NULL)
2642   {
2643     MHD_stop_daemon (plugin->http_server_daemon_v4);
2644     plugin->http_server_daemon_v4 = NULL;
2645   }
2646   if (plugin->http_server_daemon_v6 != NULL)
2647   {
2648     MHD_stop_daemon (plugin->http_server_daemon_v6);
2649     plugin->http_server_daemon_v6 = NULL;
2650   }
2651
2652   if ( plugin->http_server_task_v4 != GNUNET_SCHEDULER_NO_TASK)
2653   {
2654     GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_server_task_v4);
2655     plugin->http_server_task_v4 = GNUNET_SCHEDULER_NO_TASK;
2656   }
2657
2658   if ( plugin->http_server_task_v6 != GNUNET_SCHEDULER_NO_TASK)
2659   {
2660     GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_server_task_v6);
2661     plugin->http_server_task_v6 = GNUNET_SCHEDULER_NO_TASK;
2662   }
2663
2664   while (plugin->ipv4_addr_head!=NULL)
2665   {
2666           ipv4addr = plugin->ipv4_addr_head;
2667           GNUNET_CONTAINER_DLL_remove(plugin->ipv4_addr_head,plugin->ipv4_addr_tail,ipv4addr);
2668           GNUNET_free(ipv4addr);
2669   }
2670
2671   while (plugin->ipv6_addr_head!=NULL)
2672   {
2673           ipv6addr = plugin->ipv6_addr_head;
2674           GNUNET_CONTAINER_DLL_remove(plugin->ipv6_addr_head,plugin->ipv6_addr_tail,ipv6addr);
2675           GNUNET_free(ipv6addr);
2676   }
2677
2678   /* free all peer information */
2679   if (plugin->peers!=NULL)
2680   {
2681           GNUNET_CONTAINER_multihashmap_iterate (plugin->peers,
2682                                                                                          &remove_peer_context_Iterator,
2683                                                                                          plugin);
2684           GNUNET_CONTAINER_multihashmap_destroy (plugin->peers);
2685   }
2686   if (plugin->multi_handle!=NULL)
2687   {
2688           mret = curl_multi_cleanup(plugin->multi_handle);
2689 #if DEBUG_HTTP
2690           if ( CURLM_OK != mret)
2691                 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"curl multihandle clean up failed\n");
2692 #endif
2693           plugin->multi_handle = NULL;
2694   }
2695   curl_global_cleanup();
2696
2697   if ( plugin->http_curl_task != GNUNET_SCHEDULER_NO_TASK)
2698   {
2699     GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_curl_task);
2700     plugin->http_curl_task = GNUNET_SCHEDULER_NO_TASK;
2701   }
2702
2703   GNUNET_free_non_null (plugin->bind4_address);
2704   GNUNET_free_non_null (plugin->bind6_address);
2705   GNUNET_free_non_null(plugin->bind_hostname);
2706 #if BUILD_HTTPS
2707   GNUNET_free_non_null (plugin->crypto_init);
2708   GNUNET_free_non_null (plugin->cert);
2709   GNUNET_free_non_null (plugin->key);
2710 #endif
2711   GNUNET_free (plugin);
2712   GNUNET_free (api);
2713 #if DEBUG_HTTP
2714   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Unload %s plugin complete...\n", PROTOCOL_PREFIX);
2715 #endif
2716   return NULL;
2717 }
2718
2719 #if BUILD_HTTPS
2720 static char *
2721 load_certificate( const char * file )
2722 {
2723   struct GNUNET_DISK_FileHandle * gn_file;
2724
2725   struct stat fstat;
2726   char * text = NULL;
2727
2728   if (0!=STAT(file, &fstat))
2729           return NULL;
2730   text = GNUNET_malloc (fstat.st_size+1);
2731   gn_file = GNUNET_DISK_file_open(file,GNUNET_DISK_OPEN_READ, GNUNET_DISK_PERM_USER_READ);
2732   if (gn_file==NULL)
2733   {
2734           GNUNET_free(text);
2735           return NULL;
2736   }
2737   if (GNUNET_SYSERR == GNUNET_DISK_file_read(gn_file, text, fstat.st_size))
2738   {
2739           GNUNET_free(text);
2740           GNUNET_DISK_file_close(gn_file);
2741           return NULL;
2742   }
2743   text[fstat.st_size] = '\0';
2744   GNUNET_DISK_file_close(gn_file);
2745
2746   return text;
2747 }
2748 #endif
2749
2750
2751 /**
2752  * Entry point for the plugin.
2753  */
2754 void *
2755 LIBGNUNET_PLUGIN_TRANSPORT_INIT (void *cls)
2756 {
2757   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2758   struct Plugin *plugin;
2759   struct GNUNET_TRANSPORT_PluginFunctions *api;
2760   struct GNUNET_TIME_Relative gn_timeout;
2761   long long unsigned int port;
2762   char * component_name;
2763 #if BUILD_HTTPS
2764   char * key_file = NULL;
2765   char * cert_file = NULL;
2766 #endif
2767
2768   GNUNET_assert(cls !=NULL);
2769 #if DEBUG_HTTP
2770   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting %s plugin...\n", PROTOCOL_PREFIX);
2771 #endif
2772   GNUNET_asprintf(&component_name,"transport-%s",PROTOCOL_PREFIX);
2773
2774   plugin = GNUNET_malloc (sizeof (struct Plugin));
2775   plugin->stats = env->stats;
2776   plugin->env = env;
2777   plugin->peers = NULL;
2778   plugin->bind4_address = NULL;
2779   plugin->use_ipv6  = GNUNET_YES;
2780   plugin->use_ipv4  = GNUNET_YES;
2781
2782   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2783   api->cls = plugin;
2784   api->send = &http_plugin_send;
2785   api->disconnect = &http_plugin_disconnect;
2786   api->address_pretty_printer = &http_plugin_address_pretty_printer;
2787   api->check_address = &http_plugin_address_suggested;
2788   api->address_to_string = &http_plugin_address_to_string;
2789
2790   /* Hashing our identity to use it in URLs */
2791   GNUNET_CRYPTO_hash_to_enc ( &(plugin->env->my_identity->hashPubKey), &plugin->my_ascii_hash_ident);
2792
2793   /* Use IPv6? */
2794   if (GNUNET_CONFIGURATION_have_value (env->cfg,
2795                                                                            component_name, "USE_IPv6"))
2796     {
2797           plugin->use_ipv6 = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2798                                                                                                                            component_name,
2799                                                                                                                            "USE_IPv6");
2800     }
2801   /* Use IPv4? */
2802   if (GNUNET_CONFIGURATION_have_value (env->cfg,
2803                                                                            component_name, "USE_IPv4"))
2804     {
2805           plugin->use_ipv4 = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2806                                                         component_name,"USE_IPv4");
2807     }
2808   /* Reading port number from config file */
2809   if ((GNUNET_OK !=
2810        GNUNET_CONFIGURATION_get_value_number (env->cfg,
2811                                                                                           component_name,
2812                                               "PORT",
2813                                               &port)) ||
2814       (port > 65535) )
2815     {
2816       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2817                                            component_name,
2818                        _("Require valid port number for transport plugin `%s' in configuration!\n"),
2819                        PROTOCOL_PREFIX);
2820       GNUNET_free(component_name);
2821       LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
2822       return NULL;
2823     }
2824
2825   /* Reading ipv4 addresse to bind to from config file */
2826   if ((plugin->use_ipv4==GNUNET_YES) && (GNUNET_CONFIGURATION_have_value (env->cfg,
2827                                                                                                           component_name, "BINDTO4")))
2828   {
2829           GNUNET_break (GNUNET_OK ==
2830                                         GNUNET_CONFIGURATION_get_value_string (env->cfg,
2831                                                                                                                    component_name,
2832                                                                                                                    "BINDTO4",
2833                                                                                                                    &plugin->bind_hostname));
2834           plugin->bind4_address = GNUNET_malloc(sizeof(struct sockaddr_in));
2835           plugin->bind4_address->sin_family = AF_INET;
2836           plugin->bind4_address->sin_port = htons (port);
2837
2838           if (plugin->bind_hostname!=NULL)
2839           {
2840                   if (inet_pton(AF_INET,plugin->bind_hostname, &plugin->bind4_address->sin_addr)<=0)
2841                   {
2842                           GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2843                                                            component_name,
2844                                                            _("Misconfigured address to bind to in configuration!\n"));
2845                           GNUNET_free(plugin->bind4_address);
2846                           GNUNET_free(plugin->bind_hostname);
2847                           plugin->bind_hostname = NULL;
2848                           plugin->bind4_address = NULL;
2849                   }
2850           }
2851   }
2852
2853   /* Reading ipv4 addresse to bind to from config file */
2854   if ((plugin->use_ipv6==GNUNET_YES) && (GNUNET_CONFIGURATION_have_value (env->cfg,
2855                   component_name, "BINDTO6")))
2856   {
2857           if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (env->cfg,
2858                                                                                                                           component_name,
2859                                                                                                                           "BINDTO6",
2860                                                                                                                           &plugin->bind_hostname))
2861           {
2862                   plugin->bind6_address = GNUNET_malloc(sizeof(struct sockaddr_in6));
2863                   plugin->bind6_address->sin6_family = AF_INET6;
2864                   plugin->bind6_address->sin6_port = htons (port);
2865                   if (plugin->bind_hostname!=NULL)
2866                   {
2867                           if (inet_pton(AF_INET6,plugin->bind_hostname, &plugin->bind6_address->sin6_addr)<=0)
2868                           {
2869                                   GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2870                                                                    component_name,
2871                                                                    _("Misconfigured address to bind to in configuration!\n"));
2872                                   GNUNET_free(plugin->bind6_address);
2873                                   GNUNET_free(plugin->bind_hostname);
2874                                   plugin->bind_hostname = NULL;
2875                                   plugin->bind6_address = NULL;
2876                           }
2877                   }
2878           }
2879   }
2880
2881 #if BUILD_HTTPS
2882   /* Reading HTTPS crypto related configuration */
2883   /* Get crypto init string from config */
2884   if (GNUNET_CONFIGURATION_have_value (env->cfg,
2885                                                                            "transport-https", "CRYPTO_INIT"))
2886   {
2887                 GNUNET_CONFIGURATION_get_value_string (env->cfg,
2888                                                                                            "transport-https",
2889                                                                                            "CRYPTO_INIT",
2890                                                                                            &plugin->crypto_init);
2891   }
2892   else
2893   {
2894           GNUNET_asprintf(&plugin->crypto_init,"NORMAL");
2895   }
2896
2897 /* Get private key file from config */
2898   if (GNUNET_CONFIGURATION_have_value (env->cfg,
2899                                                                            "transport-https", "KEY_FILE"))
2900   {
2901                 GNUNET_CONFIGURATION_get_value_string (env->cfg,
2902                                                                                            "transport-https",
2903                                                                                            "KEY_FILE",
2904                                                                                            &key_file);
2905   }
2906   if (key_file==NULL)
2907           GNUNET_asprintf(&key_file,"https.key");
2908
2909 /* Get private key file from config */
2910   if (GNUNET_CONFIGURATION_have_value (env->cfg,"transport-https", "CERT_FILE"))
2911   {
2912           GNUNET_CONFIGURATION_get_value_string (env->cfg,
2913                                                                                          "transport-https",
2914                                                                                          "CERT_FILE",
2915                                                                                          &cert_file);
2916   }
2917   if (cert_file==NULL)
2918           GNUNET_asprintf(&cert_file,"https.cert");
2919
2920   /* read key & certificates from file */
2921   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Loading TLS certificate `%s' `%s'\n", key_file, cert_file);
2922
2923   plugin->key = load_certificate( key_file );
2924   plugin->cert = load_certificate( cert_file );
2925
2926   if ((plugin->key==NULL) || (plugin->cert==NULL))
2927   {
2928           char * cmd;
2929           int ret = 0;
2930           GNUNET_asprintf(&cmd,"gnunet-transport-certificate-creation %s %s", key_file, cert_file);
2931           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "No usable TLS certificate found, creating certificate \n");
2932           ret = system(cmd);
2933
2934           if (ret != 0)
2935           {
2936                   GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2937                                            "https",
2938                                                    _("Could not create a new TLS certificate, shell script `%s' failed!\n"),cmd,
2939                                                    "transport-https");
2940                   GNUNET_free (key_file);
2941                   GNUNET_free (cert_file);
2942                   GNUNET_free (component_name);
2943
2944                   LIBGNUNET_PLUGIN_TRANSPORT_DONE(api);
2945                   GNUNET_free (cmd);
2946                   return NULL;
2947           }
2948
2949           GNUNET_free (cmd);
2950
2951           plugin->key = load_certificate( key_file );
2952           plugin->cert = load_certificate( cert_file );
2953
2954           if ((plugin->key==NULL) || (plugin->cert==NULL))
2955           {
2956                   GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2957                                            "https",
2958                                                    _("No usable TLS certificate found and creating one failed! \n"),
2959                                                    "transport-https");
2960                   GNUNET_free (key_file);
2961                   GNUNET_free (cert_file);
2962                   GNUNET_free (component_name);
2963
2964                   LIBGNUNET_PLUGIN_TRANSPORT_DONE(api);
2965                   return NULL;
2966           }
2967   }
2968   GNUNET_free (key_file);
2969   GNUNET_free (cert_file);
2970
2971   GNUNET_assert((plugin->key!=NULL) && (plugin->cert!=NULL));
2972   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "TLS certificate loaded\n");
2973 #endif
2974
2975   GNUNET_assert ((port > 0) && (port <= 65535));
2976   plugin->port_inbound = port;
2977   gn_timeout = GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT;
2978   unsigned int timeout = (gn_timeout.value) / 1000;
2979   if ((plugin->http_server_daemon_v6 == NULL) && (plugin->use_ipv6 == GNUNET_YES) && (port != 0))
2980   {
2981         struct sockaddr * tmp = (struct sockaddr *) plugin->bind6_address;
2982     plugin->http_server_daemon_v6 = MHD_start_daemon (
2983 #if DEBUG_MHD
2984                                                                    MHD_USE_DEBUG |
2985 #endif
2986 #if BUILD_HTTPS
2987                                                                    MHD_USE_SSL |
2988 #endif
2989                                                                    MHD_USE_IPv6,
2990                                        port,
2991                                        &mhd_accept_cb,
2992                                        plugin , &mdh_access_cb, plugin,
2993                                        MHD_OPTION_SOCK_ADDR, tmp,
2994                                        MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 32,
2995                                        //MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 6,
2996 #if BUILD_HTTPS
2997                                        MHD_OPTION_HTTPS_PRIORITIES,  plugin->crypto_init,
2998                                        MHD_OPTION_HTTPS_MEM_KEY, plugin->key,
2999                                        MHD_OPTION_HTTPS_MEM_CERT, plugin->cert,
3000 #endif
3001                                        MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) timeout,
3002                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (2 * GNUNET_SERVER_MAX_MESSAGE_SIZE),
3003                                        MHD_OPTION_NOTIFY_COMPLETED, &mhd_termination_cb, NULL,
3004                                        MHD_OPTION_EXTERNAL_LOGGER, mhd_logger, plugin->mhd_log,
3005                                        MHD_OPTION_END);
3006   }
3007   if ((plugin->http_server_daemon_v4 == NULL) && (plugin->use_ipv4 == GNUNET_YES) && (port != 0))
3008   {
3009   plugin->http_server_daemon_v4 = MHD_start_daemon (
3010 #if DEBUG_MHD
3011                                                                    MHD_USE_DEBUG |
3012 #endif
3013 #if BUILD_HTTPS
3014                                                                    MHD_USE_SSL |
3015 #endif
3016                                                                    MHD_NO_FLAG,
3017                                        port,
3018                                        &mhd_accept_cb,
3019                                        plugin , &mdh_access_cb, plugin,
3020                                        MHD_OPTION_SOCK_ADDR, (struct sockaddr_in *)plugin->bind4_address,
3021                                        MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 32,
3022                                        //MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 6,
3023 #if BUILD_HTTPS
3024                                        MHD_OPTION_HTTPS_PRIORITIES,  plugin->crypto_init,
3025                                        MHD_OPTION_HTTPS_MEM_KEY, plugin->key,
3026                                        MHD_OPTION_HTTPS_MEM_CERT, plugin->cert,
3027 #endif
3028                                        MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) timeout,
3029                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (2 * GNUNET_SERVER_MAX_MESSAGE_SIZE),
3030                                        MHD_OPTION_NOTIFY_COMPLETED, &mhd_termination_cb, NULL,
3031                                        MHD_OPTION_EXTERNAL_LOGGER, mhd_logger, plugin->mhd_log,
3032                                        MHD_OPTION_END);
3033   }
3034   if (plugin->http_server_daemon_v4 != NULL)
3035     plugin->http_server_task_v4 = http_server_daemon_prepare (plugin, plugin->http_server_daemon_v4);
3036   if (plugin->http_server_daemon_v6 != NULL)
3037     plugin->http_server_task_v6 = http_server_daemon_prepare (plugin, plugin->http_server_daemon_v6);
3038
3039
3040   if (plugin->http_server_task_v4 != GNUNET_SCHEDULER_NO_TASK)
3041   {
3042 #if DEBUG_HTTP
3043           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD with IPv4 bound to %s with port %u\n",(plugin->bind_hostname!=NULL) ? plugin->bind_hostname : "every address",port);
3044 #endif
3045   }
3046   else if ((plugin->http_server_task_v6 != GNUNET_SCHEDULER_NO_TASK) && (plugin->http_server_task_v4 != GNUNET_SCHEDULER_NO_TASK))
3047   {
3048 #if DEBUG_HTTP
3049     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD with IPv6 bound to %s with port %u\n",(plugin->bind_hostname!=NULL) ? plugin->bind_hostname : "every address", port);
3050 #endif
3051   }
3052   else if ((plugin->http_server_task_v6 != GNUNET_SCHEDULER_NO_TASK) && (plugin->http_server_task_v4 == GNUNET_SCHEDULER_NO_TASK))
3053   {
3054 #if DEBUG_HTTP
3055     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD with IPv4 and IPv6 bound to %s with port %u\n",(plugin->bind_hostname!=NULL) ? plugin->bind_hostname : "every address", port);
3056 #endif
3057   }
3058   else
3059   {
3060         char * tmp = NULL;
3061         if ((plugin->use_ipv6 == GNUNET_YES) && (plugin->use_ipv4 == GNUNET_YES))
3062                 GNUNET_asprintf(&tmp,"with IPv4 and IPv6 enabled");
3063         if ((plugin->use_ipv6 == GNUNET_NO) && (plugin->use_ipv4 == GNUNET_YES))
3064                 GNUNET_asprintf(&tmp,"with IPv4 enabled");
3065         if ((plugin->use_ipv6 == GNUNET_YES) && (plugin->use_ipv4 == GNUNET_NO))
3066                 GNUNET_asprintf(&tmp,"with IPv6 enabled");
3067         if ((plugin->use_ipv6 == GNUNET_NO) && (plugin->use_ipv4 == GNUNET_NO))
3068                 GNUNET_asprintf(&tmp,"with NO IP PROTOCOL enabled");
3069         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,"HTTP Server with %s could not be started on port %u! %s plugin failed!\n",tmp, port, PROTOCOL_PREFIX);
3070         GNUNET_free (tmp);
3071     GNUNET_free (component_name);
3072     LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
3073     return NULL;
3074   }
3075
3076   /* Initializing cURL */
3077   curl_global_init(CURL_GLOBAL_ALL);
3078   plugin->multi_handle = curl_multi_init();
3079
3080   if ( NULL == plugin->multi_handle )
3081   {
3082     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
3083                                          component_name,
3084                                          _("Could not initialize curl multi handle, failed to start %s plugin!\n"),
3085                                          PROTOCOL_PREFIX);
3086     GNUNET_free(component_name);
3087     LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
3088     return NULL;
3089   }
3090
3091   plugin->peers = GNUNET_CONTAINER_multihashmap_create (10);
3092   GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
3093
3094   GNUNET_free(component_name);
3095   return api;
3096 }
3097
3098 /* end of plugin_transport_http.c */