Removed IPv6 linklocal check
[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   unsigned int 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           }
751       }
752       else
753       {
754           GNUNET_CONTAINER_DLL_insert(plugin->ipv4_addr_head,plugin->ipv4_addr_tail,t4);
755           plugin->env->notify_address(plugin->env->cls,PROTOCOL_PREFIX,t4, sizeof (struct IPv4HttpAddress), GNUNET_TIME_UNIT_FOREVER_REL);
756       }
757
758     }
759   else if ((af == AF_INET6) && (plugin->use_ipv6 == GNUNET_YES)  && (plugin->bind4_address == NULL))
760     {
761           struct in6_addr bnd_cmp6 = ((struct sockaddr_in6 *) addr)->sin6_addr;
762       if (IN6_IS_ADDR_LINKLOCAL (&((struct sockaddr_in6 *) addr)->sin6_addr))
763         {
764           return GNUNET_OK;
765         }
766       t6 = GNUNET_malloc(sizeof(struct IPv6HttpAddress));
767       GNUNET_assert(t6 != NULL);
768       if (plugin->bind6_address != NULL)
769       {
770           if (0 == memcmp(&plugin->bind6_address->sin6_addr, &bnd_cmp6, sizeof (struct in6_addr)))
771           {
772               memcpy (&t6->ipv6_addr,
773                       &((struct sockaddr_in6 *) addr)->sin6_addr,
774                       sizeof (struct in6_addr));
775               t6->u6_port = htons (plugin->port_inbound);
776               plugin->env->notify_address(plugin->env->cls,PROTOCOL_PREFIX,t6,sizeof (struct IPv6HttpAddress) , GNUNET_TIME_UNIT_FOREVER_REL);
777               GNUNET_CONTAINER_DLL_insert(plugin->ipv6_addr_head,plugin->ipv6_addr_tail,t6);
778           }
779       }
780       else
781       {
782           memcpy (&t6->ipv6_addr,
783                   &((struct sockaddr_in6 *) addr)->sin6_addr,
784                   sizeof (struct in6_addr));
785           t6->u6_port = htons (plugin->port_inbound);
786           GNUNET_CONTAINER_DLL_insert(plugin->ipv6_addr_head,plugin->ipv6_addr_tail,t6);
787           plugin->env->notify_address(plugin->env->cls,PROTOCOL_PREFIX,t6,sizeof (struct IPv6HttpAddress) , GNUNET_TIME_UNIT_FOREVER_REL);
788       }
789     }
790   return GNUNET_OK;
791 }
792
793
794 /**
795  * External logging function for MHD
796  * @param arg arguments
797  * @param fmt format string
798  * @param ap  list of arguments
799  */
800 void mhd_logger (void * arg, const char * fmt, va_list ap)
801 {
802         char text[1024];
803         vsnprintf(text, 1024, fmt, ap);
804         va_end(ap);
805         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,"MHD: %s \n", text);
806 }
807
808
809 static void mhd_termination_cb (void *cls, struct MHD_Connection * connection, void **httpSessionCache)
810 {
811   struct Session * ps = *httpSessionCache;
812   if (ps == NULL)
813     return;
814   struct HTTP_PeerContext * pc = ps->peercontext;
815         
816   if (connection==ps->recv_endpoint)
817   {
818 #if DEBUG_CONNECTIONS
819     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: inbound connection from peer `%s' was terminated\n", ps, GNUNET_i2s(&pc->identity));
820 #endif
821     ps->recv_active = GNUNET_NO;
822     ps->recv_connected = GNUNET_NO;
823     ps->recv_endpoint = NULL;
824   }
825   if (connection==ps->send_endpoint)
826   {
827
828     ps->send_active = GNUNET_NO;
829     ps->send_connected = GNUNET_NO;
830     ps->send_endpoint = NULL;
831 #if DEBUG_CONNECTIONS
832     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: outbound connection from peer `%s' was terminated\n", ps, GNUNET_i2s(&pc->identity));
833 #endif
834   }
835
836   /* if both connections disconnected, remove session */
837   if ((ps->send_connected == GNUNET_NO) && (ps->recv_connected == GNUNET_NO))
838   {
839       GNUNET_STATISTICS_update (pc->plugin->env->stats,
840                             gettext_noop ("# HTTP inbound sessions for peers active"),
841                             -1,
842                             GNUNET_NO);
843     remove_session(pc,ps,GNUNET_YES,GNUNET_SYSERR);
844   }
845 }
846
847 /**
848  * Callback called by MessageStreamTokenizer when a message has arrived
849  * @param cls current session as closure
850  * @param client clien
851  * @param message the message to be forwarded to transport service
852  */
853
854 static void mhd_write_mst_cb (void *cls,
855                               void *client,
856                               const struct GNUNET_MessageHeader *message)
857 {
858   struct GNUNET_TIME_Relative delay;
859   struct Session *ps  = cls;
860   GNUNET_assert(ps != NULL);
861
862   struct HTTP_PeerContext *pc = ps->peercontext;
863   GNUNET_assert(pc != NULL);
864 #if DEBUG_HTTP
865   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
866               "Connection %X: Forwarding message to transport service, type %u and size %u from `%s' (`%s')\n",
867               ps,
868               ntohs(message->type),
869               ntohs(message->size),
870               GNUNET_i2s(&(ps->peercontext)->identity),http_plugin_address_to_string(NULL,ps->addr,ps->addrlen));
871 #endif
872   delay = pc->plugin->env->receive (ps->peercontext->plugin->env->cls,
873                                                                                                                   &pc->identity,
874                                                                                                                   message, 1, ps,
875                                                                                                                   NULL,
876                                                                                                                   0);
877   pc->delay = delay;
878   if (pc->reset_task != GNUNET_SCHEDULER_NO_TASK)
879         GNUNET_SCHEDULER_cancel (pc->plugin->env->sched, pc->reset_task);
880
881   if (delay.value > 0)
882   {
883 #if DEBUG_HTTP
884         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,"Connection %X: Inbound quota management: delay next read for %llu ms \n", ps, delay.value);
885 #endif
886         pc->reset_task = GNUNET_SCHEDULER_add_delayed (pc->plugin->env->sched, delay, &reset_inbound_quota_delay, pc);
887   }
888 }
889
890 /**
891  * Check if incoming connection is accepted.
892  * NOTE: Here every connection is accepted
893  * @param cls plugin as closure
894  * @param addr address of incoming connection
895  * @param addr_len address length of incoming connection
896  * @return MHD_YES if connection is accepted, MHD_NO if connection is rejected
897  *
898  */
899 static int
900 mhd_accept_cb (void *cls, const struct sockaddr *addr, socklen_t addr_len)
901 {
902 #if 0
903   struct Plugin *plugin = cls;
904 #endif
905   /* Every connection is accepted, nothing more to do here */
906   return MHD_YES;
907 }
908
909
910 /**
911  * Callback called by MHD when it needs data to send
912  * @param cls current session
913  * @param pos position in buffer
914  * @param buf the buffer to write data to
915  * @param max max number of bytes available in buffer
916  * @return bytes written to buffer
917  */
918 static ssize_t
919 mhd_send_callback (void *cls, uint64_t pos, char *buf, size_t max)
920 {
921   struct Session * ps = cls;
922   struct HTTP_PeerContext * pc;
923   struct HTTP_Message * msg;
924   int bytes_read = 0;
925
926   GNUNET_assert (ps!=NULL);
927
928   pc = ps->peercontext;
929   msg = ps->pending_msgs_tail;
930   if (ps->send_force_disconnect==GNUNET_YES)
931   {
932 #if DEBUG_CONNECTIONS
933     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: outbound forced to disconnect\n",ps);
934 #endif
935     return -1;
936   }
937
938   if (msg!=NULL)
939   {
940     if ((msg->size-msg->pos) <= max)
941     {
942       memcpy(buf,&msg->buf[msg->pos],(msg->size-msg->pos));
943       bytes_read = msg->size-msg->pos;
944       msg->pos+=(msg->size-msg->pos);
945     }
946     else
947     {
948       memcpy(buf,&msg->buf[msg->pos],max);
949       msg->pos+=max;
950       bytes_read = max;
951     }
952
953     if (msg->pos==msg->size)
954     {
955       if (NULL!=msg->transmit_cont)
956         msg->transmit_cont (msg->transmit_cont_cls,&pc->identity,GNUNET_OK);
957       ps->queue_length_cur -= msg->size;
958       remove_http_message(ps,msg);
959     }
960   }
961   return bytes_read;
962 }
963
964 /**
965  * Process GET or PUT request received via MHD.  For
966  * GET, queue response that will send back our pending
967  * messages.  For PUT, process incoming data and send
968  * to GNUnet core.  In either case, check if a session
969  * already exists and create a new one if not.
970  */
971 static int
972 mdh_access_cb (void *cls,
973                            struct MHD_Connection *mhd_connection,
974                            const char *url,
975                            const char *method,
976                            const char *version,
977                            const char *upload_data,
978                            size_t * upload_data_size, void **httpSessionCache)
979 {
980   struct Plugin *plugin = cls;
981   struct MHD_Response *response;
982   const union MHD_ConnectionInfo * conn_info;
983
984   struct sockaddr_in  *addrin;
985   struct sockaddr_in6 *addrin6;
986
987   char address[INET6_ADDRSTRLEN+14];
988   struct GNUNET_PeerIdentity pi_in;
989   size_t id_num = 0;
990
991   struct IPv4HttpAddress ipv4addr;
992   struct IPv6HttpAddress ipv6addr;
993
994   struct HTTP_PeerContext *pc = NULL;
995   struct Session *ps = NULL;
996   struct Session *ps_tmp = NULL;
997
998   int res = GNUNET_NO;
999   int send_error_to_client;
1000   void * addr = NULL;
1001   size_t addr_len = 0 ;
1002
1003   GNUNET_assert(cls !=NULL);
1004   send_error_to_client = GNUNET_NO;
1005
1006   if (NULL == *httpSessionCache)
1007   {
1008     /* check url for peer identity , if invalid send HTTP 404*/
1009     size_t len = strlen(&url[1]);
1010     char * peer = GNUNET_malloc(104+1);
1011
1012     if ((len>104) && (url[104]==';'))
1013     {
1014         char * id = GNUNET_malloc((len-104)+1);
1015         strcpy(id,&url[105]);
1016         memcpy(peer,&url[1],103);
1017         peer[103] = '\0';
1018         id_num = strtoul ( id, NULL , 10);
1019         GNUNET_free(id);
1020     }
1021     res = GNUNET_CRYPTO_hash_from_string (peer, &(pi_in.hashPubKey));
1022     GNUNET_free(peer);
1023     if ( GNUNET_SYSERR == res )
1024     {
1025       response = MHD_create_response_from_data (strlen (HTTP_ERROR_RESPONSE),HTTP_ERROR_RESPONSE, MHD_NO, MHD_NO);
1026       res = MHD_queue_response (mhd_connection, MHD_HTTP_NOT_FOUND, response);
1027       MHD_destroy_response (response);
1028 #if DEBUG_CONNECTIONS
1029       if (res == MHD_YES)
1030         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Peer has no valid ident, sent HTTP 1.1/404\n");
1031       else
1032         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Peer has no valid ident, could not send error\n");
1033 #endif
1034       return res;
1035     }
1036   }
1037   else
1038   {
1039     ps = *httpSessionCache;
1040     pc = ps->peercontext;
1041   }
1042
1043   if (NULL == *httpSessionCache)
1044   {
1045     /* get peer context */
1046     pc = GNUNET_CONTAINER_multihashmap_get (plugin->peers, &pi_in.hashPubKey);
1047     /* Peer unknown */
1048     if (pc==NULL)
1049     {
1050       pc = GNUNET_malloc(sizeof (struct HTTP_PeerContext));
1051       pc->plugin = plugin;
1052       pc->session_id_counter=1;
1053       pc->last_session = NULL;
1054       memcpy(&pc->identity, &pi_in, sizeof(struct GNUNET_PeerIdentity));
1055       GNUNET_CONTAINER_multihashmap_put(plugin->peers, &pc->identity.hashPubKey, pc, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1056       GNUNET_STATISTICS_update (plugin->env->stats,
1057                             gettext_noop ("# HTTP peers active"),
1058                             1,
1059                             GNUNET_NO);
1060     }
1061
1062     conn_info = MHD_get_connection_info(mhd_connection, MHD_CONNECTION_INFO_CLIENT_ADDRESS );
1063     /* Incoming IPv4 connection */
1064     if ( AF_INET == conn_info->client_addr->sin_family)
1065     {
1066       addrin = conn_info->client_addr;
1067       inet_ntop(addrin->sin_family, &(addrin->sin_addr),address,INET_ADDRSTRLEN);
1068       memcpy(&ipv4addr.ipv4_addr,&(addrin->sin_addr),sizeof(struct in_addr));
1069       ipv4addr.u_port = addrin->sin_port;
1070       addr = &ipv4addr;
1071       addr_len = sizeof(struct IPv4HttpAddress);
1072     }
1073     /* Incoming IPv6 connection */
1074     if ( AF_INET6 == conn_info->client_addr->sin_family)
1075     {
1076       addrin6 = (struct sockaddr_in6 *) conn_info->client_addr;
1077       inet_ntop(addrin6->sin6_family, &(addrin6->sin6_addr),address,INET6_ADDRSTRLEN);
1078       memcpy(&ipv6addr.ipv6_addr,&(addrin6->sin6_addr),sizeof(struct in6_addr));
1079       ipv6addr.u6_port = addrin6->sin6_port;
1080       addr = &ipv6addr;
1081       addr_len = sizeof(struct IPv6HttpAddress);
1082     }
1083
1084     GNUNET_assert (addr != NULL);
1085     GNUNET_assert (addr_len != 0);
1086
1087     ps = NULL;
1088     /* only inbound sessions here */
1089
1090     ps_tmp = pc->head;
1091     while (ps_tmp!=NULL)
1092     {
1093       if ((ps_tmp->direction==INBOUND) && (ps_tmp->session_id == id_num) && (id_num!=0))
1094       {
1095         if ((ps_tmp->recv_force_disconnect!=GNUNET_YES) && (ps_tmp->send_force_disconnect!=GNUNET_YES))
1096         ps=ps_tmp;
1097         break;
1098       }
1099       ps_tmp=ps_tmp->next;
1100     }
1101
1102     if (ps==NULL)
1103     {
1104       ps = GNUNET_malloc(sizeof (struct Session));
1105       ps->addr = GNUNET_malloc(addr_len);
1106       memcpy(ps->addr,addr,addr_len);
1107       ps->addrlen = addr_len;
1108       ps->direction=INBOUND;
1109       ps->pending_msgs_head = NULL;
1110       ps->pending_msgs_tail = NULL;
1111       ps->send_connected=GNUNET_NO;
1112       ps->send_active=GNUNET_NO;
1113       ps->recv_connected=GNUNET_NO;
1114       ps->recv_active=GNUNET_NO;
1115       ps->peercontext=pc;
1116       ps->session_id =id_num;
1117           ps->queue_length_cur = 0;
1118           ps->queue_length_max = GNUNET_SERVER_MAX_MESSAGE_SIZE;
1119       ps->url = create_url (plugin, ps->addr, ps->addrlen, ps->session_id);
1120       GNUNET_CONTAINER_DLL_insert(pc->head,pc->tail,ps);
1121       GNUNET_STATISTICS_update (plugin->env->stats,
1122                             gettext_noop ("# HTTP inbound sessions for peers active"),
1123                             1,
1124                             GNUNET_NO);
1125     }
1126
1127     *httpSessionCache = ps;
1128     if (ps->msgtok==NULL)
1129       ps->msgtok = GNUNET_SERVER_mst_create (&mhd_write_mst_cb, ps);
1130 #if DEBUG_HTTP
1131     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: HTTP Daemon has new an incoming `%s' request from peer `%s' (`%s')\n",
1132                 ps,
1133                 method,
1134                 GNUNET_i2s(&pc->identity),
1135                 http_plugin_address_to_string(NULL, ps->addr, ps->addrlen));
1136 #endif
1137   }
1138
1139   /* Is it a PUT or a GET request */
1140   if (0 == strcmp (MHD_HTTP_METHOD_PUT, method))
1141   {
1142     if (ps->recv_force_disconnect == GNUNET_YES)
1143     {
1144 #if DEBUG_CONNECTIONS
1145       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: inbound connection was forced to disconnect\n",ps);
1146 #endif
1147       ps->recv_active = GNUNET_NO;
1148       return MHD_NO;
1149     }
1150     if ((*upload_data_size == 0) && (ps->recv_active==GNUNET_NO))
1151     {
1152       ps->recv_endpoint = mhd_connection;
1153       ps->recv_connected = GNUNET_YES;
1154       ps->recv_active = GNUNET_YES;
1155       ps->recv_force_disconnect = GNUNET_NO;
1156 #if DEBUG_CONNECTIONS
1157       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: inbound PUT connection connected\n",ps);
1158 #endif
1159       return MHD_YES;
1160     }
1161
1162     /* Transmission of all data complete */
1163     if ((*upload_data_size == 0) && (ps->recv_active == GNUNET_YES))
1164     {
1165       response = MHD_create_response_from_data (strlen (HTTP_PUT_RESPONSE),HTTP_PUT_RESPONSE, MHD_NO, MHD_NO);
1166       res = MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
1167 #if DEBUG_CONNECTIONS
1168       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: Sent HTTP/1.1: 200 OK as PUT Response\n",ps);
1169 #endif
1170       MHD_destroy_response (response);
1171       ps->recv_active=GNUNET_NO;
1172       return MHD_YES;
1173     }
1174
1175     /* Recieving data */
1176     if ((*upload_data_size > 0) && (ps->recv_active == GNUNET_YES))
1177     {
1178       if (pc->delay.value == 0)
1179       {
1180                   res = GNUNET_SERVER_mst_receive(ps->msgtok, ps, upload_data,*upload_data_size, GNUNET_NO, GNUNET_NO);
1181                   (*upload_data_size) = 0;
1182       }
1183       else
1184       {
1185 #if DEBUG_HTTP
1186           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);
1187 #endif
1188       }
1189       return MHD_YES;
1190     }
1191     else
1192       return MHD_NO;
1193   }
1194   if ( 0 == strcmp (MHD_HTTP_METHOD_GET, method) )
1195   {
1196     if (ps->send_force_disconnect == GNUNET_YES)
1197     {
1198 #if DEBUG_CONNECTIONS
1199       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: outbound connection was  forced to disconnect\n",ps);
1200 #endif
1201       ps->send_active = GNUNET_NO;
1202       return MHD_NO;
1203     }
1204           ps->send_connected = GNUNET_YES;
1205           ps->send_active = GNUNET_YES;
1206           ps->send_endpoint = mhd_connection;
1207           ps->send_force_disconnect = GNUNET_NO;
1208 #if DEBUG_CONNECTIONS
1209           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: inbound GET connection connected\n",ps);
1210 #endif
1211           response = MHD_create_response_from_callback(-1,32 * 1024, &mhd_send_callback, ps, NULL);
1212           res = MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
1213           MHD_destroy_response (response);
1214           return MHD_YES;
1215   }
1216   return MHD_NO;
1217 }
1218
1219 /**
1220  * Function that queries MHD's select sets and
1221  * starts the task waiting for them.
1222  * @param plugin plugin
1223  * @param daemon_handle the MHD daemon handle
1224  * @return gnunet task identifier
1225  */
1226 static GNUNET_SCHEDULER_TaskIdentifier
1227 http_server_daemon_prepare (struct Plugin *plugin , struct MHD_Daemon *daemon_handle)
1228 {
1229   GNUNET_SCHEDULER_TaskIdentifier ret;
1230   fd_set rs;
1231   fd_set ws;
1232   fd_set es;
1233   struct GNUNET_NETWORK_FDSet *wrs;
1234   struct GNUNET_NETWORK_FDSet *wws;
1235   struct GNUNET_NETWORK_FDSet *wes;
1236   int max;
1237   unsigned long long timeout;
1238   int haveto;
1239   struct GNUNET_TIME_Relative tv;
1240
1241   ret = GNUNET_SCHEDULER_NO_TASK;
1242   FD_ZERO(&rs);
1243   FD_ZERO(&ws);
1244   FD_ZERO(&es);
1245   wrs = GNUNET_NETWORK_fdset_create ();
1246   wes = GNUNET_NETWORK_fdset_create ();
1247   wws = GNUNET_NETWORK_fdset_create ();
1248   max = -1;
1249   GNUNET_assert (MHD_YES ==
1250                  MHD_get_fdset (daemon_handle,
1251                                 &rs,
1252                                 &ws,
1253                                 &es,
1254                                 &max));
1255   haveto = MHD_get_timeout (daemon_handle, &timeout);
1256   if (haveto == MHD_YES)
1257     tv.value = (uint64_t) timeout;
1258   else
1259     tv = GNUNET_TIME_UNIT_SECONDS;
1260   GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max);
1261   GNUNET_NETWORK_fdset_copy_native (wws, &ws, max);
1262   GNUNET_NETWORK_fdset_copy_native (wes, &es, max);
1263   if (daemon_handle == plugin->http_server_daemon_v4)
1264   {
1265         if (plugin->http_server_task_v4 != GNUNET_SCHEDULER_NO_TASK)
1266         {
1267                 GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_server_task_v4);
1268                 plugin->http_server_daemon_v4 = GNUNET_SCHEDULER_NO_TASK;
1269         }
1270
1271     ret = GNUNET_SCHEDULER_add_select (plugin->env->sched,
1272                                        GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1273                                        GNUNET_SCHEDULER_NO_TASK,
1274                                        tv,
1275                                        wrs,
1276                                        wws,
1277                                        &http_server_daemon_v4_run,
1278                                        plugin);
1279   }
1280   if (daemon_handle == plugin->http_server_daemon_v6)
1281   {
1282         if (plugin->http_server_task_v6 != GNUNET_SCHEDULER_NO_TASK)
1283         {
1284                 GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_server_task_v6);
1285                 plugin->http_server_task_v6 = GNUNET_SCHEDULER_NO_TASK;
1286         }
1287
1288     ret = GNUNET_SCHEDULER_add_select (plugin->env->sched,
1289                                        GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1290                                        GNUNET_SCHEDULER_NO_TASK,
1291                                        tv,
1292                                        wrs,
1293                                        wws,
1294                                        &http_server_daemon_v6_run,
1295                                        plugin);
1296   }
1297   GNUNET_NETWORK_fdset_destroy (wrs);
1298   GNUNET_NETWORK_fdset_destroy (wws);
1299   GNUNET_NETWORK_fdset_destroy (wes);
1300   return ret;
1301 }
1302
1303 /**
1304  * Call MHD IPv4 to process pending requests and then go back
1305  * and schedule the next run.
1306  * @param cls plugin as closure
1307  * @param tc task context
1308  */
1309 static void http_server_daemon_v4_run (void *cls,
1310                              const struct GNUNET_SCHEDULER_TaskContext *tc)
1311 {
1312   struct Plugin *plugin = cls;
1313
1314 #if DEBUG_SCHEDULING
1315   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY))
1316     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,"http_server_daemon_v4_run: GNUNET_SCHEDULER_REASON_READ_READY\n");      
1317   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) 
1318       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,"http_server_daemon_v4_run: GNUNET_SCHEDULER_REASON_WRITE_READY\n");  
1319   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1320       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,"http_server_daemon_v4_run: GNUNET_SCHEDULER_REASON_TIMEOUT\n");
1321   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_STARTUP))
1322       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,"http_server_daemon_v4_run: GGNUNET_SCHEDULER_REASON_STARTUP\n");        
1323   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1324       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,"http_server_daemon_v4_run: GGNUNET_SCHEDULER_REASON_SHUTDOWN\n");                 
1325 #endif              
1326       
1327   GNUNET_assert(cls !=NULL);
1328   plugin->http_server_task_v4 = GNUNET_SCHEDULER_NO_TASK;
1329
1330   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1331     return;
1332
1333   GNUNET_assert (MHD_YES == MHD_run (plugin->http_server_daemon_v4));
1334   plugin->http_server_task_v4 = http_server_daemon_prepare (plugin, plugin->http_server_daemon_v4);
1335  }
1336
1337
1338 /**
1339  * Call MHD IPv6 to process pending requests and then go back
1340  * and schedule the next run.
1341  * @param cls plugin as closure
1342  * @param tc task context
1343  */
1344 static void http_server_daemon_v6_run (void *cls,
1345                              const struct GNUNET_SCHEDULER_TaskContext *tc)
1346 {
1347   struct Plugin *plugin = cls;
1348   
1349 #if DEBUG_SCHEDULING  
1350   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY))
1351       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,"http_server_daemon_v6_run: GNUNET_SCHEDULER_REASON_READ_READY\n");
1352   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) 
1353       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,"http_server_daemon_v6_run: GNUNET_SCHEDULER_REASON_WRITE_READY\n");
1354   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1355       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,"http_server_daemon_v6_run: GNUNET_SCHEDULER_REASON_TIMEOUT\n");
1356   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_STARTUP))  
1357      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,"http_server_daemon_v6_run: GGNUNET_SCHEDULER_REASON_STARTUP\n");    
1358   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))  
1359      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,"http_server_daemon_v6_run: GGNUNET_SCHEDULER_REASON_SHUTDOWN\n"); 
1360 #endif                                            
1361
1362   GNUNET_assert(cls !=NULL);
1363   plugin->http_server_task_v6 = GNUNET_SCHEDULER_NO_TASK;
1364
1365   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1366     return;
1367
1368   GNUNET_assert (MHD_YES == MHD_run (plugin->http_server_daemon_v6));
1369   plugin->http_server_task_v6 = http_server_daemon_prepare (plugin, plugin->http_server_daemon_v6);
1370 }
1371
1372 static size_t curl_get_header_cb( void *ptr, size_t size, size_t nmemb, void *stream)
1373 {
1374   struct Session * ps = stream;
1375
1376   long http_result = 0;
1377   int res;
1378   /* Getting last http result code */
1379   GNUNET_assert(NULL!=ps);
1380   if (ps->recv_connected==GNUNET_NO)
1381   {
1382     res = curl_easy_getinfo(ps->recv_endpoint, CURLINFO_RESPONSE_CODE, &http_result);
1383     if (CURLE_OK == res)
1384     {
1385       if (http_result == 200)
1386       {
1387         ps->recv_connected = GNUNET_YES;
1388         ps->recv_active = GNUNET_YES;
1389 #if DEBUG_CONNECTIONS
1390         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: connected to recieve data\n",ps);
1391 #endif
1392         // Calling send_check_connections again since receive is established
1393         send_check_connections (ps->peercontext->plugin, ps);
1394       }
1395     }
1396   }
1397
1398 #if DEBUG_CURL
1399   char * tmp;
1400   size_t len = size * nmemb;
1401   tmp = NULL;
1402   if ((size * nmemb) < SIZE_MAX)
1403     tmp = GNUNET_malloc (len+1);
1404
1405   if ((tmp != NULL) && (len > 0))
1406   {
1407     memcpy(tmp,ptr,len);
1408     if (len>=2)
1409     {
1410       if (tmp[len-2] == 13)
1411         tmp[len-2]= '\0';
1412     }
1413     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: Header: %s\n",ps,tmp);
1414   }
1415   GNUNET_free_non_null (tmp);
1416 #endif
1417
1418   return size * nmemb;
1419 }
1420
1421 /**
1422  * Callback called by libcurl when new headers arrive
1423  * Used to get HTTP result for curl operations
1424  * @param ptr stream to read from
1425  * @param size size of one char element
1426  * @param nmemb number of char elements
1427  * @param stream closure set by user
1428  * @return bytes read by function
1429  */
1430
1431 static size_t curl_put_header_cb( void *ptr, size_t size, size_t nmemb, void *stream)
1432 {
1433   struct Session * ps = stream;
1434
1435   char * tmp;
1436   size_t len = size * nmemb;
1437   long http_result = 0;
1438   int res;
1439
1440   /* Getting last http result code */
1441   GNUNET_assert(NULL!=ps);
1442   res = curl_easy_getinfo(ps->send_endpoint, CURLINFO_RESPONSE_CODE, &http_result);
1443   if (CURLE_OK == res)
1444   {
1445     if ((http_result == 100) && (ps->send_connected==GNUNET_NO))
1446     {
1447       ps->send_connected = GNUNET_YES;
1448       ps->send_active = GNUNET_YES;
1449 #if DEBUG_CONNECTIONS
1450       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: connected to send data\n",ps);
1451 #endif
1452     }
1453     if ((http_result == 200) && (ps->send_connected==GNUNET_YES))
1454     {
1455       ps->send_connected = GNUNET_NO;
1456       ps->send_active = GNUNET_NO;
1457 #if DEBUG_CONNECTIONS
1458       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: sending disconnected\n",ps);
1459 #endif
1460     }
1461   }
1462
1463   tmp = NULL;
1464   if ((size * nmemb) < SIZE_MAX)
1465     tmp = GNUNET_malloc (len+1);
1466
1467   if ((tmp != NULL) && (len > 0))
1468   {
1469     memcpy(tmp,ptr,len);
1470     if (len>=2)
1471     {
1472       if (tmp[len-2] == 13)
1473         tmp[len-2]= '\0';
1474     }
1475   }
1476
1477   GNUNET_free_non_null (tmp);
1478
1479   return size * nmemb;
1480 }
1481
1482 /**
1483  * Callback method used with libcurl
1484  * Method is called when libcurl needs to read data during sending
1485  * @param stream pointer where to write data
1486  * @param size size of an individual element
1487  * @param nmemb count of elements that can be written to the buffer
1488  * @param ptr source pointer, passed to the libcurl handle
1489  * @return bytes written to stream
1490  */
1491 static size_t curl_send_cb(void *stream, size_t size, size_t nmemb, void *ptr)
1492 {
1493   struct Session * ps = ptr;
1494   struct HTTP_Message * msg = ps->pending_msgs_tail;
1495   size_t bytes_sent;
1496   size_t len;
1497
1498   if (ps->send_active == GNUNET_NO)
1499   {
1500         return CURL_READFUNC_PAUSE;
1501   }
1502
1503   if ((ps->pending_msgs_tail == NULL) && (ps->send_active == GNUNET_YES))
1504   {
1505 #if DEBUG_CONNECTIONS
1506     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: No Message to send, pausing connection\n",ps);
1507 #endif
1508     ps->send_active = GNUNET_NO;
1509     return CURL_READFUNC_PAUSE;
1510   }
1511
1512   GNUNET_assert (msg!=NULL);
1513
1514   /* data to send */
1515   if (msg->pos < msg->size)
1516   {
1517     /* data fit in buffer */
1518     if ((msg->size - msg->pos) <= (size * nmemb))
1519     {
1520       len = (msg->size - msg->pos);
1521       memcpy(stream, &msg->buf[msg->pos], len);
1522       msg->pos += len;
1523       bytes_sent = len;
1524     }
1525     else
1526     {
1527       len = size*nmemb;
1528       memcpy(stream, &msg->buf[msg->pos], len);
1529       msg->pos += len;
1530       bytes_sent = len;
1531     }
1532   }
1533   /* no data to send */
1534   else
1535   {
1536     bytes_sent = 0;
1537   }
1538
1539   if ( msg->pos == msg->size)
1540   {
1541 #if DEBUG_CONNECTIONS
1542           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,"Connection %X: Message with %u bytes sent, removing message from queue \n",ps, msg->pos);
1543 #endif
1544     /* Calling transmit continuation  */
1545     if (NULL != ps->pending_msgs_tail->transmit_cont)
1546       msg->transmit_cont (ps->pending_msgs_tail->transmit_cont_cls,&(ps->peercontext)->identity,GNUNET_OK);
1547     ps->queue_length_cur -= msg->size;
1548     remove_http_message(ps, msg);
1549   }
1550   return bytes_sent;
1551 }
1552
1553 static void curl_receive_mst_cb  (void *cls,
1554                                 void *client,
1555                                 const struct GNUNET_MessageHeader *message)
1556 {
1557   struct Session *ps  = cls;
1558   struct GNUNET_TIME_Relative delay;
1559   GNUNET_assert(ps != NULL);
1560
1561   struct HTTP_PeerContext *pc = ps->peercontext;
1562   GNUNET_assert(pc != NULL);
1563 #if DEBUG_HTTP
1564   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1565               "Connection %X: Forwarding message to transport service, type %u and size %u from `%s' (`%s')\n",
1566               ps,
1567               ntohs(message->type),
1568               ntohs(message->size),
1569               GNUNET_i2s(&(pc->identity)),http_plugin_address_to_string(NULL,ps->addr,ps->addrlen));
1570 #endif
1571   delay = pc->plugin->env->receive (pc->plugin->env->cls,
1572                                                                   &pc->identity,
1573                                                               message, 1, ps,
1574                                                               ps->addr,
1575                                                               ps->addrlen);
1576
1577   pc->delay = delay;
1578   if (pc->reset_task != GNUNET_SCHEDULER_NO_TASK)
1579         GNUNET_SCHEDULER_cancel (pc->plugin->env->sched, pc->reset_task);
1580
1581   if (delay.value > 0)
1582   {
1583 #if DEBUG_HTTP
1584         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,"Connection %X: Inbound quota management: delay next read for %llu ms \n", ps, delay.value);
1585 #endif
1586         pc->reset_task = GNUNET_SCHEDULER_add_delayed (pc->plugin->env->sched, delay, &reset_inbound_quota_delay, pc);
1587   }
1588 }
1589
1590
1591 /**
1592 * Callback method used with libcurl
1593 * Method is called when libcurl needs to write data during sending
1594 * @param stream pointer where to write data
1595 * @param size size of an individual element
1596 * @param nmemb count of elements that can be written to the buffer
1597 * @param ptr destination pointer, passed to the libcurl handle
1598 * @return bytes read from stream
1599 */
1600 static size_t curl_receive_cb( void *stream, size_t size, size_t nmemb, void *ptr)
1601 {
1602   struct Session * ps = ptr;
1603
1604   if (ps->peercontext->delay.value > 0)
1605   {
1606 #if DEBUG_HTTP
1607           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);
1608 #endif
1609           return (0);
1610   }
1611
1612 #if DEBUG_CONNECTIONS
1613   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: %u bytes received\n",ps, size*nmemb);
1614 #endif
1615   GNUNET_SERVER_mst_receive(ps->msgtok, ps, stream, size*nmemb, GNUNET_NO, GNUNET_NO);
1616   return (size * nmemb);
1617
1618 }
1619
1620 static void curl_handle_finished (struct Plugin *plugin)
1621 {
1622         struct Session *ps = NULL;
1623         struct HTTP_PeerContext *pc = NULL;
1624         struct CURLMsg *msg;
1625         struct HTTP_Message * cur_msg = NULL;
1626
1627         int msgs_in_queue;
1628         char * tmp;
1629         long http_result;
1630
1631         do
1632           {
1633                 msg = curl_multi_info_read (plugin->multi_handle, &msgs_in_queue);
1634                 if ((msgs_in_queue == 0) || (msg == NULL))
1635                   break;
1636                 /* get session for affected curl handle */
1637                 GNUNET_assert ( msg->easy_handle != NULL );
1638                 curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, &tmp);
1639                 ps = (struct Session *) tmp;
1640                 GNUNET_assert ( ps != NULL );
1641                 pc = ps->peercontext;
1642                 GNUNET_assert ( pc != NULL );
1643                 switch (msg->msg)
1644                   {
1645
1646                   case CURLMSG_DONE:
1647                         if ( (msg->data.result != CURLE_OK) &&
1648                                  (msg->data.result != CURLE_GOT_NOTHING) )
1649                         {
1650                           /* sending msg failed*/
1651                           if (msg->easy_handle == ps->send_endpoint)
1652                           {
1653         #if DEBUG_CONNECTIONS
1654                                 GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1655                                                    _("Connection %X: HTTP PUT to peer `%s' (`%s') failed: `%s' `%s'\n"),
1656                                                    ps,
1657                                                    GNUNET_i2s(&pc->identity),
1658                                                    http_plugin_address_to_string(NULL, ps->addr, ps->addrlen),
1659                                                    "curl_multi_perform",
1660                                                    curl_easy_strerror (msg->data.result));
1661         #endif
1662                                 ps->send_connected = GNUNET_NO;
1663                                 ps->send_active = GNUNET_NO;
1664                                 curl_multi_remove_handle(plugin->multi_handle,ps->send_endpoint);
1665                                 //curl_easy_cleanup(ps->send_endpoint);
1666                                 //ps->send_endpoint=NULL;
1667                                 while (ps->pending_msgs_tail != NULL)
1668                                 {
1669                                         cur_msg = ps->pending_msgs_tail;
1670                                         if ( NULL != cur_msg->transmit_cont)
1671                                           cur_msg->transmit_cont (cur_msg->transmit_cont_cls,&pc->identity,GNUNET_SYSERR);
1672                                         ps->queue_length_cur -= cur_msg->size;
1673                                         remove_http_message(ps,cur_msg);
1674                                 }
1675                           }
1676                           /* GET connection failed */
1677                           if (msg->easy_handle == ps->recv_endpoint)
1678                           {
1679         #if DEBUG_CONNECTIONS
1680                                 GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1681                                          _("Connection %X: HTTP GET to peer `%s' (`%s') failed: `%s' `%s'\n"),
1682                                          ps,
1683                                          GNUNET_i2s(&pc->identity),
1684                                          http_plugin_address_to_string(NULL, ps->addr, ps->addrlen),
1685                                          "curl_multi_perform",
1686                                          curl_easy_strerror (msg->data.result));
1687         #endif
1688                                 ps->recv_connected = GNUNET_NO;
1689                                 ps->recv_active = GNUNET_NO;
1690                                 curl_multi_remove_handle(plugin->multi_handle,ps->recv_endpoint);
1691                                 //curl_easy_cleanup(ps->recv_endpoint);
1692                                 //ps->recv_endpoint=NULL;
1693                           }
1694                         }
1695                         else
1696                         {
1697                           if (msg->easy_handle == ps->send_endpoint)
1698                           {
1699                                 GNUNET_assert (CURLE_OK == curl_easy_getinfo(msg->easy_handle, CURLINFO_RESPONSE_CODE, &http_result));
1700         #if DEBUG_CONNECTIONS
1701                                 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1702                                                         "Connection %X: HTTP PUT connection to peer `%s' (`%s') was closed with HTTP code %u\n",
1703                                                          ps,
1704                                                          GNUNET_i2s(&pc->identity),
1705                                                          http_plugin_address_to_string(NULL, ps->addr, ps->addrlen),
1706                                                          http_result);
1707         #endif
1708                                 /* Calling transmit continuation  */
1709                                 while (ps->pending_msgs_tail != NULL)
1710                                 {
1711                                         cur_msg = ps->pending_msgs_tail;
1712                                         if ( NULL != cur_msg->transmit_cont)
1713                                         {
1714                                                   /* HTTP 1xx : Last message before here was informational */
1715                                                   if ((http_result >=100) && (http_result < 200))
1716                                                         cur_msg->transmit_cont (cur_msg->transmit_cont_cls,&pc->identity,GNUNET_OK);
1717                                                   /* HTTP 2xx: successful operations */
1718                                                   if ((http_result >=200) && (http_result < 300))
1719                                                         cur_msg->transmit_cont (cur_msg->transmit_cont_cls,&pc->identity,GNUNET_OK);
1720                                                   /* HTTP 3xx..5xx: error */
1721                                                   if ((http_result >=300) && (http_result < 600))
1722                                                         cur_msg->transmit_cont (cur_msg->transmit_cont_cls,&pc->identity,GNUNET_SYSERR);
1723                                         }
1724                                         ps->queue_length_cur -= cur_msg->size;
1725                                         remove_http_message(ps,cur_msg);
1726                                 }
1727
1728                                 ps->send_connected = GNUNET_NO;
1729                                 ps->send_active = GNUNET_NO;
1730                                 curl_multi_remove_handle(plugin->multi_handle,ps->send_endpoint);
1731                                 //curl_easy_cleanup(ps->send_endpoint);
1732                                 //ps->send_endpoint =NULL;
1733                           }
1734                           if (msg->easy_handle == ps->recv_endpoint)
1735                           {
1736         #if DEBUG_CONNECTIONS
1737                                 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1738                                                         "Connection %X: HTTP GET connection to peer `%s' (`%s') was closed with HTTP code %u\n",
1739                                                          ps,
1740                                                          GNUNET_i2s(&pc->identity),
1741                                                          http_plugin_address_to_string(NULL, ps->addr, ps->addrlen),
1742                                                          http_result);
1743         #endif
1744                                 ps->recv_connected = GNUNET_NO;
1745                                 ps->recv_active = GNUNET_NO;
1746                                 curl_multi_remove_handle(plugin->multi_handle,ps->recv_endpoint);
1747                                 //curl_easy_cleanup(ps->recv_endpoint);
1748                                 //ps->recv_endpoint=NULL;
1749                           }
1750                         }
1751                         if ((ps->recv_connected == GNUNET_NO) && (ps->send_connected == GNUNET_NO))
1752                           remove_session (pc, ps, GNUNET_YES, GNUNET_SYSERR);
1753                         break;
1754                   default:
1755                         break;
1756                   }
1757           }
1758         while ( (msgs_in_queue > 0) );
1759 }
1760
1761
1762 /**
1763  * Task performing curl operations
1764  * @param cls plugin as closure
1765  * @param tc gnunet scheduler task context
1766  */
1767 static void curl_perform (void *cls,
1768              const struct GNUNET_SCHEDULER_TaskContext *tc)
1769 {
1770   struct Plugin *plugin = cls;
1771   static unsigned int handles_last_run;
1772   int running;
1773   CURLMcode mret;
1774
1775   GNUNET_assert(cls !=NULL);
1776
1777   plugin->http_curl_task = GNUNET_SCHEDULER_NO_TASK;
1778   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1779     return;
1780   do
1781     {
1782       running = 0;
1783       mret = curl_multi_perform (plugin->multi_handle, &running);
1784       if ((running < handles_last_run) && (running>0))
1785           curl_handle_finished(plugin);
1786       handles_last_run = running;
1787     }
1788   while (mret == CURLM_CALL_MULTI_PERFORM);
1789   curl_schedule(plugin);
1790 }
1791
1792
1793 /**
1794  * Function setting up file descriptors and scheduling task to run
1795  *
1796  * @param plugin plugin as closure
1797  * @return GNUNET_SYSERR for hard failure, GNUNET_OK for ok
1798  */
1799 static int curl_schedule(struct Plugin *plugin)
1800 {
1801   fd_set rs;
1802   fd_set ws;
1803   fd_set es;
1804   int max;
1805   struct GNUNET_NETWORK_FDSet *grs;
1806   struct GNUNET_NETWORK_FDSet *gws;
1807   long to;
1808   CURLMcode mret;
1809
1810   /* Cancel previous scheduled task */
1811   if (plugin->http_curl_task !=  GNUNET_SCHEDULER_NO_TASK)
1812   {
1813           GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_curl_task);
1814           plugin->http_curl_task = GNUNET_SCHEDULER_NO_TASK;
1815   }
1816
1817   max = -1;
1818   FD_ZERO (&rs);
1819   FD_ZERO (&ws);
1820   FD_ZERO (&es);
1821   mret = curl_multi_fdset (plugin->multi_handle, &rs, &ws, &es, &max);
1822   if (mret != CURLM_OK)
1823     {
1824       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1825                   _("%s failed at %s:%d: `%s'\n"),
1826                   "curl_multi_fdset", __FILE__, __LINE__,
1827                   curl_multi_strerror (mret));
1828       return GNUNET_SYSERR;
1829     }
1830   mret = curl_multi_timeout (plugin->multi_handle, &to);
1831   if (mret != CURLM_OK)
1832     {
1833       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1834                   _("%s failed at %s:%d: `%s'\n"),
1835                   "curl_multi_timeout", __FILE__, __LINE__,
1836                   curl_multi_strerror (mret));
1837       return GNUNET_SYSERR;
1838     }
1839
1840   grs = GNUNET_NETWORK_fdset_create ();
1841   gws = GNUNET_NETWORK_fdset_create ();
1842   GNUNET_NETWORK_fdset_copy_native (grs, &rs, max + 1);
1843   GNUNET_NETWORK_fdset_copy_native (gws, &ws, max + 1);
1844   plugin->http_curl_task = GNUNET_SCHEDULER_add_select (plugin->env->sched,
1845                                    GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1846                                    GNUNET_SCHEDULER_NO_TASK,
1847                                                                     (to == -1) ? GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5) : GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, to),
1848                                    grs,
1849                                    gws,
1850                                    &curl_perform,
1851                                    plugin);
1852   GNUNET_NETWORK_fdset_destroy (gws);
1853   GNUNET_NETWORK_fdset_destroy (grs);
1854   return GNUNET_OK;
1855 }
1856
1857 /**
1858  * Function to log curl debug messages with GNUNET_log
1859  * @param curl handle
1860  * @param type curl_infotype
1861  * @param data data
1862  * @param size size
1863  * @param cls  closure
1864  * @return 0
1865  */
1866 int curl_logger (CURL * curl, curl_infotype type , char * data, size_t size , void * cls)
1867 {
1868
1869         if (type == CURLINFO_TEXT)
1870         {
1871                 char text[size+2];
1872                 memcpy(text,data,size);
1873                 if (text[size-1] == '\n')
1874                         text[size] = '\0';
1875                 else
1876                 {
1877                         text[size] = '\n';
1878                         text[size+1] = '\0';
1879                 }
1880                 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"CURL: Connection %X - %s", cls, text);
1881         }
1882         return 0;
1883 }
1884
1885 /**
1886  * Function setting up curl handle and selecting message to send
1887  *
1888  * @param plugin plugin
1889  * @param ps session
1890  * @return GNUNET_SYSERR on failure, GNUNET_NO if connecting, GNUNET_YES if ok
1891  */
1892 static int send_check_connections (struct Plugin *plugin, struct Session *ps)
1893 {
1894   CURLMcode mret;
1895   struct HTTP_Message * msg;
1896
1897   struct GNUNET_TIME_Relative timeout = GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT;
1898
1899   if (ps->direction == OUTBOUND)
1900   {
1901     /* RECV DIRECTION */
1902     /* Check if session is connected to receive data, otherwise connect to peer */
1903     if (ps->recv_connected == GNUNET_NO)
1904     {
1905         int fresh = GNUNET_NO;
1906         if (ps->recv_endpoint == NULL)
1907         {
1908             fresh = GNUNET_YES;
1909                 ps->recv_endpoint = curl_easy_init();
1910         }
1911 #if DEBUG_CURL
1912         curl_easy_setopt(ps->recv_endpoint, CURLOPT_VERBOSE, 1L);
1913         curl_easy_setopt(ps->recv_endpoint, CURLOPT_DEBUGFUNCTION , &curl_logger);
1914         curl_easy_setopt(ps->recv_endpoint, CURLOPT_DEBUGDATA , ps->recv_endpoint);
1915 #endif
1916 #if BUILD_HTTPS
1917         curl_easy_setopt (ps->recv_endpoint, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
1918                 curl_easy_setopt(ps->recv_endpoint, CURLOPT_SSL_VERIFYPEER, 0);
1919                 curl_easy_setopt(ps->recv_endpoint, CURLOPT_SSL_VERIFYHOST, 0);
1920 #endif
1921         curl_easy_setopt(ps->recv_endpoint, CURLOPT_URL, ps->url);
1922         curl_easy_setopt(ps->recv_endpoint, CURLOPT_HEADERFUNCTION, &curl_get_header_cb);
1923         curl_easy_setopt(ps->recv_endpoint, CURLOPT_WRITEHEADER, ps);
1924         curl_easy_setopt(ps->recv_endpoint, CURLOPT_READFUNCTION, curl_send_cb);
1925         curl_easy_setopt(ps->recv_endpoint, CURLOPT_READDATA, ps);
1926         curl_easy_setopt(ps->recv_endpoint, CURLOPT_WRITEFUNCTION, curl_receive_cb);
1927         curl_easy_setopt(ps->recv_endpoint, CURLOPT_WRITEDATA, ps);
1928         curl_easy_setopt(ps->recv_endpoint, CURLOPT_TIMEOUT, (long) timeout.value);
1929         curl_easy_setopt(ps->recv_endpoint, CURLOPT_PRIVATE, ps);
1930         curl_easy_setopt(ps->recv_endpoint, CURLOPT_CONNECTTIMEOUT, HTTP_CONNECT_TIMEOUT);
1931         curl_easy_setopt(ps->recv_endpoint, CURLOPT_BUFFERSIZE, 2*GNUNET_SERVER_MAX_MESSAGE_SIZE);
1932 #if CURL_TCP_NODELAY
1933         curl_easy_setopt(ps->recv_endpoint, CURLOPT_TCP_NODELAY, 1);
1934 #endif
1935
1936         if (fresh==GNUNET_YES)
1937         {
1938                         mret = curl_multi_add_handle(plugin->multi_handle, ps->recv_endpoint);
1939                         if (mret != CURLM_OK)
1940                         {
1941                           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1942                                                   _("Connection: %X: %s failed at %s:%d: `%s'\n"),
1943                                                   ps,
1944                                                   "curl_multi_add_handle", __FILE__, __LINE__,
1945                                                   curl_multi_strerror (mret));
1946                           return GNUNET_SYSERR;
1947                         }
1948         }
1949                 if (plugin->http_curl_task !=  GNUNET_SCHEDULER_NO_TASK)
1950                 {
1951                   GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_curl_task);
1952                   plugin->http_curl_task = GNUNET_SCHEDULER_NO_TASK;
1953                 }
1954                 plugin->http_curl_task = GNUNET_SCHEDULER_add_now (plugin->env->sched, &curl_perform, plugin);
1955     }
1956
1957     /* waiting for receive direction */
1958     if (ps->recv_connected==GNUNET_NO)
1959       return GNUNET_NO;
1960
1961     /* SEND DIRECTION */
1962     /* Check if session is connected to send data, otherwise connect to peer */
1963     if ((ps->send_connected == GNUNET_YES) && (ps->send_endpoint!= NULL))
1964     {
1965       if (ps->send_active == GNUNET_YES)
1966       {
1967 #if DEBUG_CONNECTIONS
1968         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: outbound active, enqueueing message\n",ps);
1969 #endif
1970         return GNUNET_YES;
1971       }
1972       if (ps->send_active == GNUNET_NO)
1973       {
1974 #if DEBUG_CONNECTIONS
1975         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: outbound paused, unpausing existing connection and enqueueing message\n",ps);
1976 #endif
1977         if (CURLE_OK == curl_easy_pause(ps->send_endpoint,CURLPAUSE_CONT))
1978         {
1979                         ps->send_active=GNUNET_YES;
1980                         if (plugin->http_curl_task !=  GNUNET_SCHEDULER_NO_TASK)
1981                         {
1982                           GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_curl_task);
1983                           plugin->http_curl_task = GNUNET_SCHEDULER_NO_TASK;
1984                         }
1985                         plugin->http_curl_task = GNUNET_SCHEDULER_add_now (plugin->env->sched, &curl_perform, plugin);
1986                         return GNUNET_YES;
1987         }
1988         else
1989                 return GNUNET_SYSERR;
1990       }
1991     }
1992     /* not connected, initiate connection */
1993     if (ps->send_connected==GNUNET_NO)
1994     {
1995         int fresh = GNUNET_NO;
1996         if (NULL == ps->send_endpoint)
1997         {
1998                 ps->send_endpoint = curl_easy_init();
1999                 fresh = GNUNET_YES;
2000         }
2001                 GNUNET_assert (ps->send_endpoint != NULL);
2002                 GNUNET_assert (NULL != ps->pending_msgs_tail);
2003 #if DEBUG_CONNECTIONS
2004                 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: outbound not connected, initiating connection\n",ps);
2005 #endif
2006                 ps->send_active = GNUNET_NO;
2007                 msg = ps->pending_msgs_tail;
2008
2009 #if DEBUG_CURL
2010                 curl_easy_setopt(ps->send_endpoint, CURLOPT_VERBOSE, 1L);
2011         curl_easy_setopt(ps->send_endpoint, CURLOPT_DEBUGFUNCTION , &curl_logger);
2012         curl_easy_setopt(ps->send_endpoint, CURLOPT_DEBUGDATA , ps->send_endpoint);
2013 #endif
2014 #if BUILD_HTTPS
2015         curl_easy_setopt (ps->send_endpoint, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
2016                 curl_easy_setopt(ps->send_endpoint, CURLOPT_SSL_VERIFYPEER, 0);
2017                 curl_easy_setopt(ps->send_endpoint, CURLOPT_SSL_VERIFYHOST, 0);
2018 #endif
2019                 curl_easy_setopt(ps->send_endpoint, CURLOPT_URL, ps->url);
2020                 curl_easy_setopt(ps->send_endpoint, CURLOPT_PUT, 1L);
2021                 curl_easy_setopt(ps->send_endpoint, CURLOPT_HEADERFUNCTION, &curl_put_header_cb);
2022                 curl_easy_setopt(ps->send_endpoint, CURLOPT_WRITEHEADER, ps);
2023                 curl_easy_setopt(ps->send_endpoint, CURLOPT_READFUNCTION, curl_send_cb);
2024                 curl_easy_setopt(ps->send_endpoint, CURLOPT_READDATA, ps);
2025                 curl_easy_setopt(ps->send_endpoint, CURLOPT_WRITEFUNCTION, curl_receive_cb);
2026                 curl_easy_setopt(ps->send_endpoint, CURLOPT_READDATA, ps);
2027                 curl_easy_setopt(ps->send_endpoint, CURLOPT_TIMEOUT, (long) timeout.value);
2028                 curl_easy_setopt(ps->send_endpoint, CURLOPT_PRIVATE, ps);
2029                 curl_easy_setopt(ps->send_endpoint, CURLOPT_CONNECTTIMEOUT, HTTP_CONNECT_TIMEOUT);
2030                 curl_easy_setopt(ps->send_endpoint, CURLOPT_BUFFERSIZE, 2 * GNUNET_SERVER_MAX_MESSAGE_SIZE);
2031 #if CURL_TCP_NODELAY
2032                 curl_easy_setopt(ps->send_endpoint, CURLOPT_TCP_NODELAY, 1);
2033 #endif
2034
2035                 if (fresh==GNUNET_YES)
2036                 {
2037                         mret = curl_multi_add_handle(plugin->multi_handle, ps->send_endpoint);
2038                         if (mret != CURLM_OK)
2039                         {
2040                           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2041                                                   _("Connection: %X: %s failed at %s:%d: `%s'\n"),
2042                                                   ps,
2043                                                   "curl_multi_add_handle", __FILE__, __LINE__,
2044                                                   curl_multi_strerror (mret));
2045                           return GNUNET_SYSERR;
2046                         }
2047                 }
2048     }
2049         if (plugin->http_curl_task !=  GNUNET_SCHEDULER_NO_TASK)
2050         {
2051           GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_curl_task);
2052           plugin->http_curl_task = GNUNET_SCHEDULER_NO_TASK;
2053         }
2054         plugin->http_curl_task = GNUNET_SCHEDULER_add_now (plugin->env->sched, &curl_perform, plugin);
2055     return GNUNET_YES;
2056   }
2057   if (ps->direction == INBOUND)
2058   {
2059     GNUNET_assert (NULL != ps->pending_msgs_tail);
2060     if ((ps->recv_connected==GNUNET_YES) && (ps->send_connected==GNUNET_YES) &&
2061         (ps->recv_force_disconnect==GNUNET_NO) && (ps->recv_force_disconnect==GNUNET_NO))
2062         return GNUNET_YES;
2063   }
2064   return GNUNET_SYSERR;
2065 }
2066
2067 /**
2068  * select best session to transmit data to peer
2069  *
2070  * @param pc peer context of target peer
2071  * @param addr address of target peer
2072  * @param addrlen address length
2073  * @param force_address does transport service enforce address?
2074  * @param session session passed by transport service
2075  * @return selected session
2076  *
2077  */
2078 static struct Session * send_select_session (struct HTTP_PeerContext *pc, const void * addr, size_t addrlen, int force_address, struct Session * session)
2079 {
2080         struct Session * tmp = NULL;
2081         int addr_given = GNUNET_NO;
2082
2083         if ((addr!=NULL) && (addrlen>0))
2084                 addr_given = GNUNET_YES;
2085
2086         if (force_address == GNUNET_YES)
2087         {
2088                 /* check session given as argument */
2089                 if ((session != NULL) && (addr_given == GNUNET_YES))
2090                 {
2091                       if (0 == memcmp(session->addr, addr, addrlen))
2092                       {
2093                         /* connection can not be used, since it is disconnected */
2094                         if ((session->recv_force_disconnect==GNUNET_NO) && (session->send_force_disconnect==GNUNET_NO))
2095                         {
2096 #if DEBUG_SESSION_SELECTION
2097                                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Session %X selected: Using session passed by transport to send to forced address \n", session);
2098 #endif
2099                                 return session;
2100                         }
2101                       }
2102                 }
2103                 /* check last session used */
2104                 if ((pc->last_session != NULL)&& (addr_given == GNUNET_YES))
2105                 {
2106                       if (0 == memcmp(pc->last_session->addr, addr, addrlen))
2107                       {
2108                         /* connection can not be used, since it is disconnected */
2109                         if ((pc->last_session->recv_force_disconnect==GNUNET_NO) && (pc->last_session->send_force_disconnect==GNUNET_NO))
2110                         {
2111 #if DEBUG_SESSION_SELECTION
2112                                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Session %X selected: Using last session used to send to forced address \n", pc->last_session);
2113 #endif
2114                                 return pc->last_session;
2115                         }
2116                       }
2117                 }
2118                 /* find session in existing sessions */
2119                 tmp = pc->head;
2120                 while ((tmp!=NULL) && (addr_given == GNUNET_YES))
2121                 {
2122
2123                           if (0 == memcmp(tmp->addr, addr, addrlen))
2124                       {
2125                         /* connection can not be used, since it is disconnected */
2126                         if ((tmp->recv_force_disconnect==GNUNET_NO) && (tmp->send_force_disconnect==GNUNET_NO))
2127                         {
2128 #if DEBUG_SESSION_SELECTION
2129                                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Session %X selected: Using existing session to send to forced address \n", session);
2130 #endif
2131                                   return session;
2132                         }
2133
2134                       }
2135                           tmp=tmp->next;
2136                 }
2137                 /* no session to use */
2138                 return NULL;
2139         }
2140         if ((force_address == GNUNET_NO) || (force_address == GNUNET_SYSERR))
2141         {
2142                 /* check session given as argument */
2143                 if (session != NULL)
2144                 {
2145                         /* connection can not be used, since it is disconnected */
2146                         if ((session->recv_force_disconnect==GNUNET_NO) && (session->send_force_disconnect==GNUNET_NO))
2147                         {
2148 #if DEBUG_SESSION_SELECTION
2149                                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Session %X selected: Using session passed by transport to send not-forced address \n", session);
2150 #endif
2151                                   return session;
2152                         }
2153
2154                 }
2155                 /* check last session used */
2156                 if (pc->last_session != NULL)
2157                 {
2158                         /* connection can not be used, since it is disconnected */
2159                         if ((pc->last_session->recv_force_disconnect==GNUNET_NO) && (pc->last_session->send_force_disconnect==GNUNET_NO))
2160                         {
2161 #if DEBUG_SESSION_SELECTION
2162                                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Session %X selected: Using last session to send to not-forced address \n", pc->last_session);
2163 #endif
2164                                 return pc->last_session;
2165                         }
2166                 }
2167                 /* find session in existing sessions */
2168                 tmp = pc->head;
2169                 while (tmp!=NULL)
2170                 {
2171                         /* connection can not be used, since it is disconnected */
2172                         if ((tmp->recv_force_disconnect==GNUNET_NO) && (tmp->send_force_disconnect==GNUNET_NO))
2173                         {
2174 #if DEBUG_SESSION_SELECTION
2175                                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Session %X selected: Using existing session to send to not-forced address \n", tmp);
2176 #endif
2177                                 return tmp;
2178                         }
2179                         tmp=tmp->next;
2180                 }
2181                 return NULL;
2182         }
2183         return NULL;
2184 }
2185
2186 /**
2187  * Function that can be used by the transport service to transmit
2188  * a message using the plugin.   Note that in the case of a
2189  * peer disconnecting, the continuation MUST be called
2190  * prior to the disconnect notification itself.  This function
2191  * will be called with this peer's HELLO message to initiate
2192  * a fresh connection to another peer.
2193  *
2194  * @param cls closure
2195  * @param target who should receive this message
2196  * @param msgbuf the message to transmit
2197  * @param msgbuf_size number of bytes in 'msgbuf'
2198  * @param priority how important is the message (most plugins will
2199  *                 ignore message priority and just FIFO)
2200  * @param to how long to wait at most for the transmission (does not
2201  *                require plugins to discard the message after the timeout,
2202  *                just advisory for the desired delay; most plugins will ignore
2203  *                this as well)
2204  * @param session which session must be used (or NULL for "any")
2205  * @param addr the address to use (can be NULL if the plugin
2206  *                is "on its own" (i.e. re-use existing TCP connection))
2207  * @param addrlen length of the address in bytes
2208  * @param force_address GNUNET_YES if the plugin MUST use the given address,
2209  *                GNUNET_NO means the plugin may use any other address and
2210  *                GNUNET_SYSERR means that only reliable existing
2211  *                bi-directional connections should be used (regardless
2212  *                of address)
2213  * @param cont continuation to call once the message has
2214  *        been transmitted (or if the transport is ready
2215  *        for the next transmission call; or if the
2216  *        peer disconnected...); can be NULL
2217  * @param cont_cls closure for cont
2218  * @return number of bytes used (on the physical network, with overheads);
2219  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
2220  *         and does NOT mean that the message was not transmitted (DV)
2221  */
2222 static ssize_t
2223 http_plugin_send (void *cls,
2224                   const struct GNUNET_PeerIdentity *target,
2225                   const char *msgbuf,
2226                   size_t msgbuf_size,
2227                   unsigned int priority,
2228                   struct GNUNET_TIME_Relative to,
2229                   struct Session *session,
2230                   const void *addr,
2231                   size_t addrlen,
2232                   int force_address,
2233                   GNUNET_TRANSPORT_TransmitContinuation cont,
2234                   void *cont_cls)
2235 {
2236   struct Plugin *plugin = cls;
2237   struct HTTP_Message *msg;
2238   struct HTTP_PeerContext * pc;
2239   struct Session * ps = NULL;
2240
2241   GNUNET_assert(cls !=NULL);
2242
2243 #if DEBUG_HTTP
2244   char * force;
2245   if (force_address == GNUNET_YES)
2246           GNUNET_asprintf(&force, "forced addr.");
2247   if (force_address == GNUNET_NO)
2248           GNUNET_asprintf(&force, "any addr.");
2249   if (force_address == GNUNET_SYSERR)
2250           GNUNET_asprintf(&force,"reliable bi-direc. address addr.");
2251
2252   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Transport tells me to send %u bytes to `%s' using %s (%s) and session: %X\n",
2253                                       msgbuf_size,
2254                                       GNUNET_i2s(target),
2255                                       force,
2256                                       http_plugin_address_to_string(NULL, addr, addrlen),
2257                                       session);
2258
2259   GNUNET_free(force);
2260 #endif
2261
2262   pc = GNUNET_CONTAINER_multihashmap_get (plugin->peers, &target->hashPubKey);
2263   /* Peer unknown */
2264   if (pc==NULL)
2265   {
2266     pc = GNUNET_malloc(sizeof (struct HTTP_PeerContext));
2267     pc->plugin = plugin;
2268     pc->session_id_counter=1;
2269     pc->last_session = NULL;
2270     memcpy(&pc->identity, target, sizeof(struct GNUNET_PeerIdentity));
2271     GNUNET_CONTAINER_multihashmap_put(plugin->peers, &pc->identity.hashPubKey, pc, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2272     GNUNET_STATISTICS_update (plugin->env->stats,
2273                             gettext_noop ("# HTTP peers active"),
2274                             1,
2275                             GNUNET_NO);
2276   }
2277
2278   ps = send_select_session (pc, addr, addrlen, force_address, session);
2279
2280   /* session not existing, but address forced -> creating new session */
2281   if (ps==NULL)
2282   {
2283         if ((addr!=NULL) && (addrlen!=0))
2284         {
2285       ps = GNUNET_malloc(sizeof (struct Session));
2286 #if DEBUG_SESSION_SELECTION
2287       if (force_address == GNUNET_YES)
2288          GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"No existing connection & forced address: creating new session %X to peer %s\n", ps, GNUNET_i2s(target));
2289       if (force_address != GNUNET_YES)
2290          GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"No existing connection: creating new session %X to peer %s\n", ps, GNUNET_i2s(target));
2291 #endif
2292       if ((addrlen!=0) && (addr!=NULL))
2293       {
2294          ps->addr = GNUNET_malloc(addrlen);
2295          memcpy(ps->addr,addr,addrlen);
2296          ps->addrlen = addrlen;
2297       }
2298           else
2299           {
2300                 ps->addr = NULL;
2301                 ps->addrlen = 0;
2302           }
2303           ps->direction=OUTBOUND;
2304           ps->recv_connected = GNUNET_NO;
2305           ps->recv_force_disconnect = GNUNET_NO;
2306           ps->send_connected = GNUNET_NO;
2307           ps->send_force_disconnect = GNUNET_NO;
2308           ps->pending_msgs_head = NULL;
2309           ps->pending_msgs_tail = NULL;
2310           ps->peercontext=pc;
2311           ps->session_id = pc->session_id_counter;
2312           ps->queue_length_cur = 0;
2313           ps->queue_length_max = GNUNET_SERVER_MAX_MESSAGE_SIZE;
2314           pc->session_id_counter++;
2315           ps->url = create_url (plugin, ps->addr, ps->addrlen, ps->session_id);
2316           if (ps->msgtok == NULL)
2317                         ps->msgtok = GNUNET_SERVER_mst_create (&curl_receive_mst_cb, ps);
2318           GNUNET_CONTAINER_DLL_insert(pc->head,pc->tail,ps);
2319           GNUNET_STATISTICS_update (plugin->env->stats,
2320                                                                 gettext_noop ("# HTTP outbound sessions for peers active"),
2321                                                                 1,
2322                                                                 GNUNET_NO);
2323         }
2324         else
2325         {
2326 #if DEBUG_HTTP
2327                 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));
2328 #endif
2329                 return GNUNET_SYSERR;
2330     }
2331   }
2332
2333   if (msgbuf_size >= (ps->queue_length_max - ps->queue_length_cur))
2334   {
2335         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);
2336         //return GNUNET_SYSERR;
2337   }
2338
2339         /* create msg */
2340         msg = GNUNET_malloc (sizeof (struct HTTP_Message) + msgbuf_size);
2341         msg->next = NULL;
2342         msg->size = msgbuf_size;
2343         msg->pos = 0;
2344         msg->buf = (char *) &msg[1];
2345         msg->transmit_cont = cont;
2346         msg->transmit_cont_cls = cont_cls;
2347         memcpy (msg->buf,msgbuf, msgbuf_size);
2348
2349         GNUNET_CONTAINER_DLL_insert(ps->pending_msgs_head,ps->pending_msgs_tail,msg);
2350         ps->queue_length_cur += msgbuf_size;
2351
2352         if (send_check_connections (plugin, ps) == GNUNET_SYSERR)
2353           return GNUNET_SYSERR;
2354           if (force_address != GNUNET_YES)
2355                   pc->last_session = ps;
2356
2357           if (pc->last_session==NULL)
2358                   pc->last_session = ps;
2359           return msg->size;
2360 }
2361
2362
2363
2364 /**
2365  * Function that can be used to force the plugin to disconnect
2366  * from the given peer and cancel all previous transmissions
2367  * (and their continuationc).
2368  *
2369  * @param cls closure
2370  * @param target peer from which to disconnect
2371  */
2372 static void
2373 http_plugin_disconnect (void *cls,
2374                             const struct GNUNET_PeerIdentity *target)
2375 {
2376
2377
2378   struct Plugin *plugin = cls;
2379   struct HTTP_PeerContext *pc = NULL;
2380   struct Session *ps = NULL;
2381   //struct Session *tmp = NULL;
2382
2383   pc = GNUNET_CONTAINER_multihashmap_get (plugin->peers, &target->hashPubKey);
2384   if (pc==NULL)
2385     return;
2386   ps = pc->head;
2387
2388   while (ps!=NULL)
2389   {
2390     /* Telling transport that session is getting disconnected */
2391     plugin->env->session_end(plugin, target, ps);
2392     if (ps->direction==OUTBOUND)
2393     {
2394       if (ps->send_endpoint!=NULL)
2395       {
2396         //GNUNET_assert(CURLM_OK == curl_multi_remove_handle(plugin->multi_handle,ps->send_endpoint));
2397         //curl_easy_cleanup(ps->send_endpoint);
2398         //ps->send_endpoint=NULL;
2399         ps->send_force_disconnect = GNUNET_YES;
2400       }
2401       if (ps->recv_endpoint!=NULL)
2402       {
2403        //GNUNET_assert(CURLM_OK == curl_multi_remove_handle(plugin->multi_handle,ps->recv_endpoint));
2404        //curl_easy_cleanup(ps->recv_endpoint);
2405        //ps->recv_endpoint=NULL;
2406        ps->recv_force_disconnect = GNUNET_YES;
2407       }
2408     }
2409
2410     if (ps->direction==INBOUND)
2411     {
2412       ps->recv_force_disconnect = GNUNET_YES;
2413       ps->send_force_disconnect = GNUNET_YES;
2414     }
2415
2416     while (ps->pending_msgs_head!=NULL)
2417     {
2418       remove_http_message(ps, ps->pending_msgs_head);
2419     }
2420     ps->recv_active = GNUNET_NO;
2421     ps->send_active = GNUNET_NO;
2422     ps=ps->next;
2423   }
2424 }
2425
2426
2427 /**
2428  * Convert the transports address to a nice, human-readable
2429  * format.
2430  *
2431  * @param cls closure
2432  * @param type name of the transport that generated the address
2433  * @param addr one of the addresses of the host, NULL for the last address
2434  *        the specific address format depends on the transport
2435  * @param addrlen length of the address
2436  * @param numeric should (IP) addresses be displayed in numeric form?
2437  * @param timeout after how long should we give up?
2438  * @param asc function to call on each string
2439  * @param asc_cls closure for asc
2440  */
2441 static void
2442 http_plugin_address_pretty_printer (void *cls,
2443                                         const char *type,
2444                                         const void *addr,
2445                                         size_t addrlen,
2446                                         int numeric,
2447                                         struct GNUNET_TIME_Relative timeout,
2448                                         GNUNET_TRANSPORT_AddressStringCallback
2449                                         asc, void *asc_cls)
2450 {
2451   const struct IPv4HttpAddress *t4;
2452   const struct IPv6HttpAddress *t6;
2453   struct sockaddr_in a4;
2454   struct sockaddr_in6 a6;
2455   char * address;
2456   char * ret;
2457   unsigned int port;
2458   unsigned int res;
2459
2460   GNUNET_assert(cls !=NULL);
2461   if (addrlen == sizeof (struct IPv6HttpAddress))
2462   {
2463     address = GNUNET_malloc (INET6_ADDRSTRLEN);
2464     t6 = addr;
2465     a6.sin6_addr = t6->ipv6_addr;
2466     inet_ntop(AF_INET6, &(a6.sin6_addr),address,INET6_ADDRSTRLEN);
2467     port = ntohs(t6->u6_port);
2468   }
2469   else if (addrlen == sizeof (struct IPv4HttpAddress))
2470   {
2471     address = GNUNET_malloc (INET_ADDRSTRLEN);
2472     t4 = addr;
2473     a4.sin_addr.s_addr =  t4->ipv4_addr;
2474     inet_ntop(AF_INET, &(a4.sin_addr),address,INET_ADDRSTRLEN);
2475     port = ntohs(t4->u_port);
2476   }
2477   else
2478   {
2479     /* invalid address */
2480     GNUNET_break_op (0);
2481     asc (asc_cls, NULL);
2482     return;
2483   }
2484   res = GNUNET_asprintf(&ret,"%s://%s:%u/", PROTOCOL_PREFIX, address, port);
2485   GNUNET_free (address);
2486   GNUNET_assert(res != 0);
2487   asc (asc_cls, ret);
2488   GNUNET_free_non_null (ret);
2489 }
2490
2491
2492
2493 /**
2494  * Another peer has suggested an address for this
2495  * peer and transport plugin.  Check that this could be a valid
2496  * address.  If so, consider adding it to the list
2497  * of addresses.
2498  *
2499  * @param cls closure
2500  * @param addr pointer to the address
2501  * @param addrlen length of addr
2502  * @return GNUNET_OK if this is a plausible address for this peer
2503  *         and transport
2504  */
2505 static int
2506 http_plugin_address_suggested (void *cls,
2507                                const void *addr, size_t addrlen)
2508 {
2509   struct Plugin *plugin = cls;
2510   struct IPv4HttpAddress *v4;
2511   struct IPv6HttpAddress *v6;
2512
2513   struct IPv4HttpAddress *tv4 = plugin->ipv4_addr_head;
2514   struct IPv6HttpAddress *tv6 = plugin->ipv6_addr_head;
2515   int res;
2516   unsigned int port;
2517
2518   GNUNET_assert(cls !=NULL);
2519   if ((addrlen != sizeof (struct IPv4HttpAddress)) &&
2520       (addrlen != sizeof (struct IPv6HttpAddress)))
2521     {
2522       return GNUNET_SYSERR;
2523     }
2524   if (addrlen == sizeof (struct IPv4HttpAddress))
2525     {
2526       v4 = (struct IPv4HttpAddress *) addr;
2527       /* Not skipping loopback
2528       if (INADDR_LOOPBACK == ntohl(v4->ipv4_addr))
2529       {
2530         return GNUNET_SYSERR;
2531       } */
2532
2533       if (plugin->bind4_address!=NULL)
2534       {
2535           res = memcmp (&plugin->bind4_address->sin_addr, &v4->ipv4_addr, sizeof(uint32_t));
2536           if ((res==0) && (ntohs (v4->u_port) == plugin->port_inbound))
2537                   return GNUNET_OK;
2538           else
2539                   return GNUNET_SYSERR;
2540       }
2541
2542       while (tv4!=NULL)
2543       {
2544           res = memcmp (&tv4->ipv4_addr, &v4->ipv4_addr, sizeof(uint32_t));
2545           if ((res==0) && (v4->u_port == tv4->u_port) && (ntohs (v4->u_port) == plugin->port_inbound))
2546                   return GNUNET_OK;
2547           tv4 = tv4->next;
2548       }
2549       port = ntohs (v4->u_port);
2550       if (port != plugin->port_inbound)
2551       {
2552         return GNUNET_SYSERR;
2553       }
2554     }
2555   if (addrlen == sizeof (struct IPv6HttpAddress))
2556     {
2557       v6 = (struct IPv6HttpAddress *) addr;
2558
2559       if (plugin->bind6_address!=NULL)
2560       {
2561           res = memcmp (&plugin->bind6_address->sin6_addr, &v6->ipv6_addr, sizeof(struct in6_addr));
2562           if ((res==0) && (ntohs (v6->u6_port) == plugin->port_inbound))
2563                   return GNUNET_OK;
2564           else
2565                   return GNUNET_SYSERR;
2566       }
2567
2568       while (tv6!=NULL)
2569       {
2570           res = memcmp (&tv6->ipv6_addr, &v6->ipv6_addr, sizeof(struct in6_addr));
2571           if ((res==0) && (v6->u6_port == tv6->u6_port) && (ntohs (v6->u6_port) == plugin->port_inbound))
2572                   return GNUNET_OK;
2573           tv6 = tv6->next;
2574       }
2575     }
2576
2577   return GNUNET_SYSERR;
2578 }
2579
2580
2581 /**
2582  * Function called for a quick conversion of the binary address to
2583  * a numeric address.  Note that the caller must not free the
2584  * address and that the next call to this function is allowed
2585  * to override the address again.
2586  *
2587  * @param cls closure
2588  * @param addr binary address
2589  * @param addrlen length of the address
2590  * @return string representing the same address
2591  */
2592 static const char*
2593 http_plugin_address_to_string (void *cls,
2594                                    const void *addr,
2595                                    size_t addrlen)
2596 {
2597   const struct IPv4HttpAddress *t4;
2598   const struct IPv6HttpAddress *t6;
2599   struct sockaddr_in a4;
2600   struct sockaddr_in6 a6;
2601   char * address;
2602   char * ret;
2603   uint16_t port;
2604   unsigned int res;
2605
2606   if (addrlen == sizeof (struct IPv6HttpAddress))
2607     {
2608       address = GNUNET_malloc (INET6_ADDRSTRLEN);
2609       t6 = addr;
2610       a6.sin6_addr = t6->ipv6_addr;
2611       inet_ntop(AF_INET6, &(a6.sin6_addr),address,INET6_ADDRSTRLEN);
2612       port = ntohs(t6->u6_port);
2613     }
2614   else if (addrlen == sizeof (struct IPv4HttpAddress))
2615     {
2616       address = GNUNET_malloc (INET_ADDRSTRLEN);
2617       t4 = addr;
2618       a4.sin_addr.s_addr =  t4->ipv4_addr;
2619       inet_ntop(AF_INET, &(a4.sin_addr),address,INET_ADDRSTRLEN);
2620       port = ntohs(t4->u_port);
2621     }
2622   else
2623     {
2624       /* invalid address */
2625       return NULL;
2626     }
2627   res = GNUNET_asprintf(&ret,"%s:%u",address,port);
2628   GNUNET_free (address);
2629   GNUNET_assert(res != 0);
2630   return ret;
2631 }
2632
2633
2634 /**
2635  * Exit point from the plugin.
2636  */
2637 void *
2638 LIBGNUNET_PLUGIN_TRANSPORT_DONE (void *cls)
2639 {
2640   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2641   struct Plugin *plugin = api->cls;
2642   CURLMcode mret;
2643   struct IPv4HttpAddress * ipv4addr;
2644   struct IPv6HttpAddress * ipv6addr;
2645   GNUNET_assert(cls !=NULL);
2646
2647   if (plugin->http_server_daemon_v4 != NULL)
2648   {
2649     MHD_stop_daemon (plugin->http_server_daemon_v4);
2650     plugin->http_server_daemon_v4 = NULL;
2651   }
2652   if (plugin->http_server_daemon_v6 != NULL)
2653   {
2654     MHD_stop_daemon (plugin->http_server_daemon_v6);
2655     plugin->http_server_daemon_v6 = NULL;
2656   }
2657
2658   if ( plugin->http_server_task_v4 != GNUNET_SCHEDULER_NO_TASK)
2659   {
2660     GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_server_task_v4);
2661     plugin->http_server_task_v4 = GNUNET_SCHEDULER_NO_TASK;
2662   }
2663
2664   if ( plugin->http_server_task_v6 != GNUNET_SCHEDULER_NO_TASK)
2665   {
2666     GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_server_task_v6);
2667     plugin->http_server_task_v6 = GNUNET_SCHEDULER_NO_TASK;
2668   }
2669
2670   while (plugin->ipv4_addr_head!=NULL)
2671   {
2672           ipv4addr = plugin->ipv4_addr_head;
2673           GNUNET_CONTAINER_DLL_remove(plugin->ipv4_addr_head,plugin->ipv4_addr_tail,ipv4addr);
2674           GNUNET_free(ipv4addr);
2675   }
2676
2677   while (plugin->ipv6_addr_head!=NULL)
2678   {
2679           ipv6addr = plugin->ipv6_addr_head;
2680           GNUNET_CONTAINER_DLL_remove(plugin->ipv6_addr_head,plugin->ipv6_addr_tail,ipv6addr);
2681           GNUNET_free(ipv6addr);
2682   }
2683
2684   /* free all peer information */
2685   if (plugin->peers!=NULL)
2686   {
2687           GNUNET_CONTAINER_multihashmap_iterate (plugin->peers,
2688                                                                                          &remove_peer_context_Iterator,
2689                                                                                          plugin);
2690           GNUNET_CONTAINER_multihashmap_destroy (plugin->peers);
2691   }
2692   if (plugin->multi_handle!=NULL)
2693   {
2694           mret = curl_multi_cleanup(plugin->multi_handle);
2695 #if DEBUG_HTTP
2696           if ( CURLM_OK != mret)
2697                 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"curl multihandle clean up failed\n");
2698 #endif
2699           plugin->multi_handle = NULL;
2700   }
2701   curl_global_cleanup();
2702
2703   if ( plugin->http_curl_task != GNUNET_SCHEDULER_NO_TASK)
2704   {
2705     GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_curl_task);
2706     plugin->http_curl_task = GNUNET_SCHEDULER_NO_TASK;
2707   }
2708
2709   GNUNET_free_non_null (plugin->bind4_address);
2710   GNUNET_free_non_null (plugin->bind6_address);
2711   GNUNET_free_non_null(plugin->bind_hostname);
2712 #if BUILD_HTTPS
2713   GNUNET_free_non_null (plugin->crypto_init);
2714   GNUNET_free_non_null (plugin->cert);
2715   GNUNET_free_non_null (plugin->key);
2716 #endif
2717   GNUNET_free (plugin);
2718   GNUNET_free (api);
2719 #if DEBUG_HTTP
2720   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Unload %s plugin complete...\n", PROTOCOL_PREFIX);
2721 #endif
2722   return NULL;
2723 }
2724
2725 #if BUILD_HTTPS
2726 static char *
2727 load_certificate( const char * file )
2728 {
2729   struct GNUNET_DISK_FileHandle * gn_file;
2730
2731   struct stat fstat;
2732   char * text = NULL;
2733
2734   if (0!=STAT(file, &fstat))
2735           return NULL;
2736   text = GNUNET_malloc (fstat.st_size+1);
2737   gn_file = GNUNET_DISK_file_open(file,GNUNET_DISK_OPEN_READ, GNUNET_DISK_PERM_USER_READ);
2738   if (gn_file==NULL)
2739   {
2740           GNUNET_free(text);
2741           return NULL;
2742   }
2743   if (GNUNET_SYSERR == GNUNET_DISK_file_read(gn_file, text, fstat.st_size))
2744   {
2745           GNUNET_free(text);
2746           GNUNET_DISK_file_close(gn_file);
2747           return NULL;
2748   }
2749   text[fstat.st_size] = '\0';
2750   GNUNET_DISK_file_close(gn_file);
2751
2752   return text;
2753 }
2754 #endif
2755
2756
2757 /**
2758  * Entry point for the plugin.
2759  */
2760 void *
2761 LIBGNUNET_PLUGIN_TRANSPORT_INIT (void *cls)
2762 {
2763   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2764   struct Plugin *plugin;
2765   struct GNUNET_TRANSPORT_PluginFunctions *api;
2766   struct GNUNET_TIME_Relative gn_timeout;
2767   long long unsigned int port;
2768   char * component_name;
2769 #if BUILD_HTTPS
2770   char * key_file = NULL;
2771   char * cert_file = NULL;
2772 #endif
2773
2774   GNUNET_assert(cls !=NULL);
2775 #if DEBUG_HTTP
2776   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting %s plugin...\n", PROTOCOL_PREFIX);
2777 #endif
2778   GNUNET_asprintf(&component_name,"transport-%s",PROTOCOL_PREFIX);
2779
2780   plugin = GNUNET_malloc (sizeof (struct Plugin));
2781   plugin->stats = env->stats;
2782   plugin->env = env;
2783   plugin->peers = NULL;
2784   plugin->bind4_address = NULL;
2785   plugin->use_ipv6  = GNUNET_YES;
2786   plugin->use_ipv4  = GNUNET_YES;
2787
2788   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2789   api->cls = plugin;
2790   api->send = &http_plugin_send;
2791   api->disconnect = &http_plugin_disconnect;
2792   api->address_pretty_printer = &http_plugin_address_pretty_printer;
2793   api->check_address = &http_plugin_address_suggested;
2794   api->address_to_string = &http_plugin_address_to_string;
2795
2796   /* Hashing our identity to use it in URLs */
2797   GNUNET_CRYPTO_hash_to_enc ( &(plugin->env->my_identity->hashPubKey), &plugin->my_ascii_hash_ident);
2798
2799   /* Use IPv6? */
2800   if (GNUNET_CONFIGURATION_have_value (env->cfg,
2801                                                                            component_name, "USE_IPv6"))
2802     {
2803           plugin->use_ipv6 = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2804                                                                                                                            component_name,
2805                                                                                                                            "USE_IPv6");
2806     }
2807   /* Use IPv4? */
2808   if (GNUNET_CONFIGURATION_have_value (env->cfg,
2809                                                                            component_name, "USE_IPv4"))
2810     {
2811           plugin->use_ipv4 = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2812                                                         component_name,"USE_IPv4");
2813     }
2814   /* Reading port number from config file */
2815   if ((GNUNET_OK !=
2816        GNUNET_CONFIGURATION_get_value_number (env->cfg,
2817                                                                                           component_name,
2818                                               "PORT",
2819                                               &port)) ||
2820       (port > 65535) )
2821     {
2822       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2823                                            component_name,
2824                        _("Require valid port number for transport plugin `%s' in configuration!\n"),
2825                        PROTOCOL_PREFIX);
2826       GNUNET_free(component_name);
2827       LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
2828       return NULL;
2829     }
2830
2831   /* Reading ipv4 addresse to bind to from config file */
2832   if ((plugin->use_ipv4==GNUNET_YES) && (GNUNET_CONFIGURATION_have_value (env->cfg,
2833                                                                                                           component_name, "BINDTO4")))
2834   {
2835           GNUNET_break (GNUNET_OK ==
2836                                         GNUNET_CONFIGURATION_get_value_string (env->cfg,
2837                                                                                                                    component_name,
2838                                                                                                                    "BINDTO4",
2839                                                                                                                    &plugin->bind_hostname));
2840           plugin->bind4_address = GNUNET_malloc(sizeof(struct sockaddr_in));
2841           plugin->bind4_address->sin_family = AF_INET;
2842           plugin->bind4_address->sin_port = htons (port);
2843
2844           if (plugin->bind_hostname!=NULL)
2845           {
2846                   if (inet_pton(AF_INET,plugin->bind_hostname, &plugin->bind4_address->sin_addr)<=0)
2847                   {
2848                           GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2849                                                            component_name,
2850                                                            _("Misconfigured address to bind to in configuration!\n"));
2851                           GNUNET_free(plugin->bind4_address);
2852                           GNUNET_free(plugin->bind_hostname);
2853                           plugin->bind_hostname = NULL;
2854                           plugin->bind4_address = NULL;
2855                   }
2856           }
2857   }
2858
2859   /* Reading ipv4 addresse to bind to from config file */
2860   if ((plugin->use_ipv6==GNUNET_YES) && (GNUNET_CONFIGURATION_have_value (env->cfg,
2861                   component_name, "BINDTO6")))
2862   {
2863           if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (env->cfg,
2864                                                                                                                           component_name,
2865                                                                                                                           "BINDTO6",
2866                                                                                                                           &plugin->bind_hostname))
2867           {
2868                   plugin->bind6_address = GNUNET_malloc(sizeof(struct sockaddr_in6));
2869                   plugin->bind6_address->sin6_family = AF_INET6;
2870                   plugin->bind6_address->sin6_port = htons (port);
2871                   if (plugin->bind_hostname!=NULL)
2872                   {
2873                           if (inet_pton(AF_INET6,plugin->bind_hostname, &plugin->bind6_address->sin6_addr)<=0)
2874                           {
2875                                   GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2876                                                                    component_name,
2877                                                                    _("Misconfigured address to bind to in configuration!\n"));
2878                                   GNUNET_free(plugin->bind6_address);
2879                                   GNUNET_free(plugin->bind_hostname);
2880                                   plugin->bind_hostname = NULL;
2881                                   plugin->bind6_address = NULL;
2882                           }
2883                   }
2884           }
2885   }
2886
2887 #if BUILD_HTTPS
2888   /* Reading HTTPS crypto related configuration */
2889   /* Get crypto init string from config */
2890   if (GNUNET_CONFIGURATION_have_value (env->cfg,
2891                                                                            "transport-https", "CRYPTO_INIT"))
2892   {
2893                 GNUNET_CONFIGURATION_get_value_string (env->cfg,
2894                                                                                            "transport-https",
2895                                                                                            "CRYPTO_INIT",
2896                                                                                            &plugin->crypto_init);
2897   }
2898   else
2899   {
2900           GNUNET_asprintf(&plugin->crypto_init,"NORMAL");
2901   }
2902
2903 /* Get private key file from config */
2904   if (GNUNET_CONFIGURATION_have_value (env->cfg,
2905                                                                            "transport-https", "KEY_FILE"))
2906   {
2907                 GNUNET_CONFIGURATION_get_value_string (env->cfg,
2908                                                                                            "transport-https",
2909                                                                                            "KEY_FILE",
2910                                                                                            &key_file);
2911   }
2912   if (key_file==NULL)
2913           GNUNET_asprintf(&key_file,"https.key");
2914
2915 /* Get private key file from config */
2916   if (GNUNET_CONFIGURATION_have_value (env->cfg,"transport-https", "CERT_FILE"))
2917   {
2918           GNUNET_CONFIGURATION_get_value_string (env->cfg,
2919                                                                                          "transport-https",
2920                                                                                          "CERT_FILE",
2921                                                                                          &cert_file);
2922   }
2923   if (cert_file==NULL)
2924           GNUNET_asprintf(&cert_file,"https.cert");
2925
2926   /* read key & certificates from file */
2927   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Loading TLS certificate `%s' `%s'\n", key_file, cert_file);
2928
2929   plugin->key = load_certificate( key_file );
2930   plugin->cert = load_certificate( cert_file );
2931
2932   if ((plugin->key==NULL) || (plugin->cert==NULL))
2933   {
2934           char * cmd;
2935           int ret = 0;
2936           GNUNET_asprintf(&cmd,"gnunet-transport-certificate-creation %s %s", key_file, cert_file);
2937           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "No usable TLS certificate found, creating certificate \n");
2938           ret = system(cmd);
2939
2940           if (ret != 0)
2941           {
2942                   GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2943                                            "https",
2944                                                    _("Could not create a new TLS certificate, shell script `%s' failed!\n"),cmd,
2945                                                    "transport-https");
2946                   GNUNET_free (key_file);
2947                   GNUNET_free (cert_file);
2948                   GNUNET_free (component_name);
2949
2950                   LIBGNUNET_PLUGIN_TRANSPORT_DONE(api);
2951                   GNUNET_free (cmd);
2952                   return NULL;
2953           }
2954
2955           GNUNET_free (cmd);
2956
2957           plugin->key = load_certificate( key_file );
2958           plugin->cert = load_certificate( cert_file );
2959
2960           if ((plugin->key==NULL) || (plugin->cert==NULL))
2961           {
2962                   GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2963                                            "https",
2964                                                    _("No usable TLS certificate found and creating one failed! \n"),
2965                                                    "transport-https");
2966                   GNUNET_free (key_file);
2967                   GNUNET_free (cert_file);
2968                   GNUNET_free (component_name);
2969
2970                   LIBGNUNET_PLUGIN_TRANSPORT_DONE(api);
2971                   return NULL;
2972           }
2973   }
2974   GNUNET_free (key_file);
2975   GNUNET_free (cert_file);
2976
2977   GNUNET_assert((plugin->key!=NULL) && (plugin->cert!=NULL));
2978   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "TLS certificate loaded\n");
2979 #endif
2980
2981   GNUNET_assert ((port > 0) && (port <= 65535));
2982   plugin->port_inbound = port;
2983   gn_timeout = GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT;
2984   unsigned int timeout = (gn_timeout.value) / 1000;
2985   if ((plugin->http_server_daemon_v6 == NULL) && (plugin->use_ipv6 == GNUNET_YES) && (port != 0))
2986   {
2987         struct sockaddr * tmp = (struct sockaddr *) plugin->bind6_address;
2988     plugin->http_server_daemon_v6 = MHD_start_daemon (
2989 #if DEBUG_MHD
2990                                                                    MHD_USE_DEBUG |
2991 #endif
2992 #if BUILD_HTTPS
2993                                                                    MHD_USE_SSL |
2994 #endif
2995                                                                    MHD_USE_IPv6,
2996                                        port,
2997                                        &mhd_accept_cb,
2998                                        plugin , &mdh_access_cb, plugin,
2999                                        MHD_OPTION_SOCK_ADDR, tmp,
3000                                        MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 32,
3001                                        //MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 6,
3002 #if BUILD_HTTPS
3003                                        MHD_OPTION_HTTPS_PRIORITIES,  plugin->crypto_init,
3004                                        MHD_OPTION_HTTPS_MEM_KEY, plugin->key,
3005                                        MHD_OPTION_HTTPS_MEM_CERT, plugin->cert,
3006 #endif
3007                                        MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) timeout,
3008                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (2 * GNUNET_SERVER_MAX_MESSAGE_SIZE),
3009                                        MHD_OPTION_NOTIFY_COMPLETED, &mhd_termination_cb, NULL,
3010                                        MHD_OPTION_EXTERNAL_LOGGER, mhd_logger, plugin->mhd_log,
3011                                        MHD_OPTION_END);
3012   }
3013   if ((plugin->http_server_daemon_v4 == NULL) && (plugin->use_ipv4 == GNUNET_YES) && (port != 0))
3014   {
3015   plugin->http_server_daemon_v4 = MHD_start_daemon (
3016 #if DEBUG_MHD
3017                                                                    MHD_USE_DEBUG |
3018 #endif
3019 #if BUILD_HTTPS
3020                                                                    MHD_USE_SSL |
3021 #endif
3022                                                                    MHD_NO_FLAG,
3023                                        port,
3024                                        &mhd_accept_cb,
3025                                        plugin , &mdh_access_cb, plugin,
3026                                        MHD_OPTION_SOCK_ADDR, (struct sockaddr_in *)plugin->bind4_address,
3027                                        MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 32,
3028                                        //MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 6,
3029 #if BUILD_HTTPS
3030                                        MHD_OPTION_HTTPS_PRIORITIES,  plugin->crypto_init,
3031                                        MHD_OPTION_HTTPS_MEM_KEY, plugin->key,
3032                                        MHD_OPTION_HTTPS_MEM_CERT, plugin->cert,
3033 #endif
3034                                        MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) timeout,
3035                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (2 * GNUNET_SERVER_MAX_MESSAGE_SIZE),
3036                                        MHD_OPTION_NOTIFY_COMPLETED, &mhd_termination_cb, NULL,
3037                                        MHD_OPTION_EXTERNAL_LOGGER, mhd_logger, plugin->mhd_log,
3038                                        MHD_OPTION_END);
3039   }
3040   if (plugin->http_server_daemon_v4 != NULL)
3041     plugin->http_server_task_v4 = http_server_daemon_prepare (plugin, plugin->http_server_daemon_v4);
3042   if (plugin->http_server_daemon_v6 != NULL)
3043     plugin->http_server_task_v6 = http_server_daemon_prepare (plugin, plugin->http_server_daemon_v6);
3044
3045
3046   if (plugin->http_server_task_v4 != GNUNET_SCHEDULER_NO_TASK)
3047   {
3048 #if DEBUG_HTTP
3049           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);
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 IPv6 bound to %s with port %u\n",(plugin->bind_hostname!=NULL) ? plugin->bind_hostname : "every address", port);
3056 #endif
3057   }
3058   else if ((plugin->http_server_task_v6 != GNUNET_SCHEDULER_NO_TASK) && (plugin->http_server_task_v4 == GNUNET_SCHEDULER_NO_TASK))
3059   {
3060 #if DEBUG_HTTP
3061     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);
3062 #endif
3063   }
3064   else
3065   {
3066         char * tmp = NULL;
3067         if ((plugin->use_ipv6 == GNUNET_YES) && (plugin->use_ipv4 == GNUNET_YES))
3068                 GNUNET_asprintf(&tmp,"with IPv4 and IPv6 enabled");
3069         if ((plugin->use_ipv6 == GNUNET_NO) && (plugin->use_ipv4 == GNUNET_YES))
3070                 GNUNET_asprintf(&tmp,"with IPv4 enabled");
3071         if ((plugin->use_ipv6 == GNUNET_YES) && (plugin->use_ipv4 == GNUNET_NO))
3072                 GNUNET_asprintf(&tmp,"with IPv6 enabled");
3073         if ((plugin->use_ipv6 == GNUNET_NO) && (plugin->use_ipv4 == GNUNET_NO))
3074                 GNUNET_asprintf(&tmp,"with NO IP PROTOCOL enabled");
3075         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);
3076         GNUNET_free (tmp);
3077     GNUNET_free (component_name);
3078     LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
3079     return NULL;
3080   }
3081
3082   /* Initializing cURL */
3083   curl_global_init(CURL_GLOBAL_ALL);
3084   plugin->multi_handle = curl_multi_init();
3085
3086   if ( NULL == plugin->multi_handle )
3087   {
3088     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
3089                                          component_name,
3090                                          _("Could not initialize curl multi handle, failed to start %s plugin!\n"),
3091                                          PROTOCOL_PREFIX);
3092     GNUNET_free(component_name);
3093     LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
3094     return NULL;
3095   }
3096
3097   plugin->peers = GNUNET_CONTAINER_multihashmap_create (10);
3098   GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
3099
3100   GNUNET_free(component_name);
3101   return api;
3102 }
3103
3104 /* end of plugin_transport_http.c */