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