9893cd27cc3e42d2866c81419cd1872cb050c4e8
[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_free(msg);
489     GNUNET_CONTAINER_DLL_remove(ps->pending_msgs_head,ps->pending_msgs_head,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       t6 = GNUNET_malloc(sizeof(struct IPv6HttpAddress));
612       if (IN6_IS_ADDR_LINKLOCAL (&((struct sockaddr_in6 *) addr)->sin6_addr))
613         {
614           return GNUNET_OK;
615         }
616
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   struct HTTP_PeerContext *pc = ps->peercontext;
690   GNUNET_assert(ps != NULL);
691   GNUNET_assert(pc != NULL);
692 #if DEBUG_HTTP
693   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
694               "Connection %X: Forwarding message to transport service, type %u and size %u from `%s' (`%s')\n",
695               ps,
696               ntohs(message->type),
697               ntohs(message->size),
698               GNUNET_i2s(&(ps->peercontext)->identity),http_plugin_address_to_string(NULL,ps->addr,ps->addrlen));
699 #endif
700   pc->plugin->env->receive (ps->peercontext->plugin->env->cls,
701                             &pc->identity,
702                             message, 1, ps,
703                             NULL,
704                             0);
705 }
706
707 /**
708  * Check if ip is allowed to connect.
709  */
710 static int
711 mhd_accept_cb (void *cls,
712                       const struct sockaddr *addr, socklen_t addr_len)
713 {
714 #if 0
715   struct Plugin *plugin = cls;
716 #endif
717   /* Every connection is accepted, nothing more to do here */
718   return MHD_YES;
719 }
720
721 int mhd_send_callback (void *cls, uint64_t pos, char *buf, int max)
722 {
723   int bytes_read = 0;
724
725   struct Session * ps = cls;
726   struct HTTP_PeerContext * pc;
727   struct HTTP_Message * msg;
728
729   GNUNET_assert (ps!=NULL);
730   pc = ps->peercontext;
731   msg = ps->pending_msgs_tail;
732   if (ps->send_force_disconnect==GNUNET_YES)
733   {
734 #if DEBUG_CONNECTIONS
735     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: outbound forced to disconnect\n",ps);
736 #endif
737     return -1;
738   }
739
740   if (msg!=NULL)
741   {
742     if ((msg->size-msg->pos) <= max)
743     {
744       memcpy(buf,&msg->buf[msg->pos],(msg->size-msg->pos));
745       bytes_read = msg->size-msg->pos;
746       msg->pos+=(msg->size-msg->pos);
747     }
748     else
749     {
750       memcpy(buf,&msg->buf[msg->pos],max);
751       msg->pos+=max;
752       bytes_read = max;
753     }
754
755     if (msg->pos==msg->size)
756     {
757       if (NULL!=msg->transmit_cont)
758         msg->transmit_cont (msg->transmit_cont_cls,&pc->identity,GNUNET_OK);
759       remove_http_message(ps,msg);
760     }
761   }
762   return bytes_read;
763 }
764
765 /**
766  * Process GET or PUT request received via MHD.  For
767  * GET, queue response that will send back our pending
768  * messages.  For PUT, process incoming data and send
769  * to GNUnet core.  In either case, check if a session
770  * already exists and create a new one if not.
771  */
772 static int
773 mdh_access_cb (void *cls,
774                        struct MHD_Connection *mhd_connection,
775                        const char *url,
776                        const char *method,
777                        const char *version,
778                        const char *upload_data,
779                        size_t * upload_data_size, void **httpSessionCache)
780 {
781   struct Plugin *plugin = cls;
782   struct MHD_Response *response;
783   const union MHD_ConnectionInfo * conn_info;
784
785   struct sockaddr_in  *addrin;
786   struct sockaddr_in6 *addrin6;
787
788   char address[INET6_ADDRSTRLEN+14];
789   struct GNUNET_PeerIdentity pi_in;
790   size_t id_num = 0;
791
792   struct IPv4HttpAddress ipv4addr;
793   struct IPv6HttpAddress ipv6addr;
794
795   struct HTTP_PeerContext *pc;
796   struct Session *ps = NULL;
797   struct Session *ps_tmp = NULL;
798
799   int res = GNUNET_NO;
800   int send_error_to_client;
801   void * addr;
802   size_t addr_len;
803
804   GNUNET_assert(cls !=NULL);
805   send_error_to_client = GNUNET_NO;
806
807   if (NULL == *httpSessionCache)
808   {
809     /* check url for peer identity , if invalid send HTTP 404*/
810     size_t len = strlen(&url[1]);
811     char * peer = GNUNET_malloc(104+1);
812
813     if ((len>104) && (url[104]==';'))
814     {
815         char * id = GNUNET_malloc((len-104)+1);
816         strcpy(id,&url[105]);
817         memcpy(peer,&url[1],103);
818         peer[103] = '\0';
819         id_num = strtoul ( id, NULL , 10);
820         GNUNET_free(id);
821     }
822     res = GNUNET_CRYPTO_hash_from_string (peer, &(pi_in.hashPubKey));
823     GNUNET_free(peer);
824     if ( GNUNET_SYSERR == res )
825     {
826       response = MHD_create_response_from_data (strlen (HTTP_ERROR_RESPONSE),HTTP_ERROR_RESPONSE, MHD_NO, MHD_NO);
827       res = MHD_queue_response (mhd_connection, MHD_HTTP_NOT_FOUND, response);
828       MHD_destroy_response (response);
829 #if DEBUG_CONNECTIONS
830       if (res == MHD_YES)
831         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Peer has no valid ident, sent HTTP 1.1/404\n");
832       else
833         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Peer has no valid ident, could not send error\n");
834 #endif
835       return res;
836     }
837   }
838   else
839   {
840     ps = *httpSessionCache;
841     pc = ps->peercontext;
842   }
843
844   if (NULL == *httpSessionCache)
845   {
846     /* get peer context */
847     pc = GNUNET_CONTAINER_multihashmap_get (plugin->peers, &pi_in.hashPubKey);
848     /* Peer unknown */
849     if (pc==NULL)
850     {
851       pc = GNUNET_malloc(sizeof (struct HTTP_PeerContext));
852       pc->plugin = plugin;
853       pc->session_id_counter=1;
854       pc->last_session = NULL;
855       memcpy(&pc->identity, &pi_in, sizeof(struct GNUNET_PeerIdentity));
856       GNUNET_CONTAINER_multihashmap_put(plugin->peers, &pc->identity.hashPubKey, pc, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
857       GNUNET_STATISTICS_update (plugin->env->stats,
858                             gettext_noop ("# HTTP peers active"),
859                             1,
860                             GNUNET_NO);
861     }
862
863     conn_info = MHD_get_connection_info(mhd_connection, MHD_CONNECTION_INFO_CLIENT_ADDRESS );
864     /* Incoming IPv4 connection */
865     if ( AF_INET == conn_info->client_addr->sin_family)
866     {
867       addrin = conn_info->client_addr;
868       inet_ntop(addrin->sin_family, &(addrin->sin_addr),address,INET_ADDRSTRLEN);
869       memcpy(&ipv4addr.ipv4_addr,&(addrin->sin_addr),sizeof(struct in_addr));
870       ipv4addr.u_port = addrin->sin_port;
871       addr = &ipv4addr;
872       addr_len = sizeof(struct IPv4HttpAddress);
873     }
874     /* Incoming IPv6 connection */
875     if ( AF_INET6 == conn_info->client_addr->sin_family)
876     {
877       addrin6 = (struct sockaddr_in6 *) conn_info->client_addr;
878       inet_ntop(addrin6->sin6_family, &(addrin6->sin6_addr),address,INET6_ADDRSTRLEN);
879       memcpy(&ipv6addr.ipv6_addr,&(addrin6->sin6_addr),sizeof(struct in6_addr));
880       ipv6addr.u6_port = addrin6->sin6_port;
881       addr = &ipv6addr;
882       addr_len = sizeof(struct IPv6HttpAddress);
883     }
884
885     ps = NULL;
886     /* only inbound sessions here */
887
888     ps_tmp = pc->head;
889     while (ps_tmp!=NULL)
890     {
891       if ((ps_tmp->direction==INBOUND) && (ps_tmp->session_id == id_num) && (id_num!=0))
892       {
893         if ((ps_tmp->recv_force_disconnect!=GNUNET_YES) && (ps_tmp->send_force_disconnect!=GNUNET_YES))
894         ps=ps_tmp;
895         break;
896       }
897       ps_tmp=ps_tmp->next;
898     }
899
900     if (ps==NULL)
901     {
902       ps = GNUNET_malloc(sizeof (struct Session));
903       ps->addr = GNUNET_malloc(addr_len);
904       memcpy(ps->addr,addr,addr_len);
905       ps->addrlen = addr_len;
906       ps->direction=INBOUND;
907       ps->pending_msgs_head = NULL;
908       ps->pending_msgs_tail = NULL;
909       ps->send_connected=GNUNET_NO;
910       ps->send_active=GNUNET_NO;
911       ps->recv_connected=GNUNET_NO;
912       ps->recv_active=GNUNET_NO;
913       ps->peercontext=pc;
914       ps->session_id =id_num;
915       ps->url = create_url (plugin, ps->addr, ps->addrlen, ps->session_id);
916       GNUNET_CONTAINER_DLL_insert(pc->head,pc->tail,ps);
917       GNUNET_STATISTICS_update (plugin->env->stats,
918                             gettext_noop ("# HTTP inbound sessions for peers active"),
919                             1,
920                             GNUNET_NO);
921     }
922
923     *httpSessionCache = ps;
924     if (ps->msgtok==NULL)
925       ps->msgtok = GNUNET_SERVER_mst_create (&mhd_write_mst_cb, ps);
926 #if DEBUG_HTTP
927     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: HTTP Daemon has new an incoming `%s' request from peer `%s' (`%s')\n",
928                 ps,
929                 method,
930                 GNUNET_i2s(&pc->identity),
931                 http_plugin_address_to_string(NULL, ps->addr, ps->addrlen));
932 #endif
933   }
934
935   /* Is it a PUT or a GET request */
936   if (0 == strcmp (MHD_HTTP_METHOD_PUT, method))
937   {
938     if (ps->recv_force_disconnect == GNUNET_YES)
939     {
940 #if DEBUG_CONNECTIONS
941       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: inbound connection was forced to disconnect\n",ps);
942 #endif
943       ps->recv_active = GNUNET_NO;
944       return MHD_NO;
945     }
946     if ((*upload_data_size == 0) && (ps->recv_active==GNUNET_NO))
947     {
948       ps->recv_endpoint = mhd_connection;
949       ps->recv_connected = GNUNET_YES;
950       ps->recv_active = GNUNET_YES;
951       ps->recv_force_disconnect = GNUNET_NO;
952 #if DEBUG_CONNECTIONS
953       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: inbound PUT connection connected\n",ps);
954 #endif
955       return MHD_YES;
956     }
957
958     /* Transmission of all data complete */
959     if ((*upload_data_size == 0) && (ps->recv_active == GNUNET_YES))
960     {
961       response = MHD_create_response_from_data (strlen (HTTP_PUT_RESPONSE),HTTP_PUT_RESPONSE, MHD_NO, MHD_NO);
962       res = MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
963 #if DEBUG_CONNECTIONS
964       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: Sent HTTP/1.1: 200 OK as PUT Response\n",ps);
965 #endif
966       MHD_destroy_response (response);
967       ps->recv_active=GNUNET_NO;
968       return MHD_YES;
969     }
970
971     /* Recieving data */
972     if ((*upload_data_size > 0) && (ps->recv_active == GNUNET_YES))
973     {
974       res = GNUNET_SERVER_mst_receive(ps->msgtok, ps, upload_data,*upload_data_size, GNUNET_NO, GNUNET_NO);
975       (*upload_data_size) = 0;
976       return MHD_YES;
977     }
978     else
979       return MHD_NO;
980   }
981   if ( 0 == strcmp (MHD_HTTP_METHOD_GET, method) )
982   {
983     if (ps->send_force_disconnect == GNUNET_YES)
984     {
985 #if DEBUG_CONNECTIONS
986       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: outbound connection was  forced to disconnect\n",ps);
987 #endif
988       ps->send_active = GNUNET_NO;
989       return MHD_NO;
990     }
991           ps->send_connected = GNUNET_YES;
992           ps->send_active = GNUNET_YES;
993           ps->send_endpoint = mhd_connection;
994           ps->send_force_disconnect = GNUNET_NO;
995 #if DEBUG_CONNECTIONS
996           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: inbound GET connection connected\n",ps);
997 #endif
998           response = MHD_create_response_from_callback(-1,32 * 1024, &mhd_send_callback, ps, NULL);
999           res = MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
1000           MHD_destroy_response (response);
1001           return MHD_YES;
1002   }
1003   return MHD_NO;
1004 }
1005
1006 /**
1007  * Function that queries MHD's select sets and
1008  * starts the task waiting for them.
1009  */
1010 static GNUNET_SCHEDULER_TaskIdentifier
1011 http_server_daemon_prepare (void * cls, struct MHD_Daemon *daemon_handle)
1012 {
1013   struct Plugin *plugin = cls;
1014   GNUNET_SCHEDULER_TaskIdentifier ret;
1015   fd_set rs;
1016   fd_set ws;
1017   fd_set es;
1018   struct GNUNET_NETWORK_FDSet *wrs;
1019   struct GNUNET_NETWORK_FDSet *wws;
1020   struct GNUNET_NETWORK_FDSet *wes;
1021   int max;
1022   unsigned long long timeout;
1023   int haveto;
1024   struct GNUNET_TIME_Relative tv;
1025
1026   GNUNET_assert(cls !=NULL);
1027   ret = GNUNET_SCHEDULER_NO_TASK;
1028   FD_ZERO(&rs);
1029   FD_ZERO(&ws);
1030   FD_ZERO(&es);
1031   wrs = GNUNET_NETWORK_fdset_create ();
1032   wes = GNUNET_NETWORK_fdset_create ();
1033   wws = GNUNET_NETWORK_fdset_create ();
1034   max = -1;
1035   GNUNET_assert (MHD_YES ==
1036                  MHD_get_fdset (daemon_handle,
1037                                 &rs,
1038                                 &ws,
1039                                 &es,
1040                                 &max));
1041   haveto = MHD_get_timeout (daemon_handle, &timeout);
1042   if (haveto == MHD_YES)
1043     tv.value = (uint64_t) timeout;
1044   else
1045     tv = GNUNET_TIME_UNIT_FOREVER_REL;
1046   GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max);
1047   GNUNET_NETWORK_fdset_copy_native (wws, &ws, max);
1048   GNUNET_NETWORK_fdset_copy_native (wes, &es, max);
1049   if (daemon_handle == plugin->http_server_daemon_v4)
1050   {
1051         if (plugin->http_server_task_v4 != GNUNET_SCHEDULER_NO_TASK)
1052         {
1053                 GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_server_task_v4);
1054                 plugin->http_server_daemon_v4 = GNUNET_SCHEDULER_NO_TASK;
1055         }
1056
1057     ret = GNUNET_SCHEDULER_add_select (plugin->env->sched,
1058                                        GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1059                                        GNUNET_SCHEDULER_NO_TASK,
1060                                        tv,
1061                                        wrs,
1062                                        wws,
1063                                        &http_server_daemon_v4_run,
1064                                        plugin);
1065   }
1066   if (daemon_handle == plugin->http_server_daemon_v6)
1067   {
1068         if (plugin->http_server_task_v6 != GNUNET_SCHEDULER_NO_TASK)
1069         {
1070                 GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_server_task_v6);
1071                 plugin->http_server_task_v6 = GNUNET_SCHEDULER_NO_TASK;
1072         }
1073
1074     ret = GNUNET_SCHEDULER_add_select (plugin->env->sched,
1075                                        GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1076                                        GNUNET_SCHEDULER_NO_TASK,
1077                                        tv,
1078                                        wrs,
1079                                        wws,
1080                                        &http_server_daemon_v6_run,
1081                                        plugin);
1082   }
1083   GNUNET_NETWORK_fdset_destroy (wrs);
1084   GNUNET_NETWORK_fdset_destroy (wws);
1085   GNUNET_NETWORK_fdset_destroy (wes);
1086   return ret;
1087 }
1088
1089 /**
1090  * Call MHD to process pending requests and then go back
1091  * and schedule the next run.
1092  */
1093 static void http_server_daemon_v4_run (void *cls,
1094                              const struct GNUNET_SCHEDULER_TaskContext *tc)
1095 {
1096   struct Plugin *plugin = cls;
1097
1098   GNUNET_assert(cls !=NULL);
1099   plugin->http_server_task_v4 = GNUNET_SCHEDULER_NO_TASK;
1100
1101   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1102     return;
1103
1104   GNUNET_assert (MHD_YES == MHD_run (plugin->http_server_daemon_v4));
1105   plugin->http_server_task_v4 = http_server_daemon_prepare (plugin, plugin->http_server_daemon_v4);
1106   return;
1107 }
1108
1109
1110 /**
1111  * Call MHD to process pending requests and then go back
1112  * and schedule the next run.
1113  */
1114 static void http_server_daemon_v6_run (void *cls,
1115                              const struct GNUNET_SCHEDULER_TaskContext *tc)
1116 {
1117   struct Plugin *plugin = cls;
1118
1119   GNUNET_assert(cls !=NULL);
1120   plugin->http_server_task_v6 = GNUNET_SCHEDULER_NO_TASK;
1121
1122   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1123     return;
1124
1125   GNUNET_assert (MHD_YES == MHD_run (plugin->http_server_daemon_v6));
1126   plugin->http_server_task_v6 = http_server_daemon_prepare (plugin, plugin->http_server_daemon_v6);
1127   return;
1128 }
1129
1130 static size_t curl_get_header_cb( void *ptr, size_t size, size_t nmemb, void *stream)
1131 {
1132   struct Session * ps = stream;
1133
1134   long http_result = 0;
1135   int res;
1136   /* Getting last http result code */
1137   if (ps->recv_connected==GNUNET_NO)
1138   {
1139     GNUNET_assert(NULL!=ps);
1140     res = curl_easy_getinfo(ps->recv_endpoint, CURLINFO_RESPONSE_CODE, &http_result);
1141     if (CURLE_OK == res)
1142     {
1143       if (http_result == 200)
1144       {
1145         ps->recv_connected = GNUNET_YES;
1146         ps->recv_active = GNUNET_YES;
1147 #if DEBUG_CONNECTIONS
1148         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: connected to recieve data\n",ps);
1149 #endif
1150         // Calling send_check_connections again since receive is established
1151         send_check_connections (ps->peercontext->plugin, ps);
1152       }
1153     }
1154   }
1155
1156 #if DEBUG_CURL
1157   char * tmp;
1158   size_t len = size * nmemb;
1159   tmp = NULL;
1160   if ((size * nmemb) < SIZE_MAX)
1161     tmp = GNUNET_malloc (len+1);
1162
1163   if ((tmp != NULL) && (len > 0))
1164   {
1165     memcpy(tmp,ptr,len);
1166     if (len>=2)
1167     {
1168       if (tmp[len-2] == 13)
1169         tmp[len-2]= '\0';
1170     }
1171     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: Header: %s\n",ps,tmp);
1172   }
1173   if (NULL != tmp)
1174     GNUNET_free (tmp);
1175 #endif
1176
1177   return size * nmemb;
1178 }
1179
1180 static size_t curl_put_header_cb( void *ptr, size_t size, size_t nmemb, void *stream)
1181 {
1182   struct Session * ps = stream;
1183
1184   char * tmp;
1185   size_t len = size * nmemb;
1186   long http_result = 0;
1187   int res;
1188
1189   /* Getting last http result code */
1190   GNUNET_assert(NULL!=ps);
1191   res = curl_easy_getinfo(ps->send_endpoint, CURLINFO_RESPONSE_CODE, &http_result);
1192   if (CURLE_OK == res)
1193   {
1194     if ((http_result == 100) && (ps->send_connected==GNUNET_NO))
1195     {
1196       ps->send_connected = GNUNET_YES;
1197       ps->send_active = GNUNET_YES;
1198 #if DEBUG_CONNECTIONS
1199       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: connected to send data\n",ps);
1200 #endif
1201     }
1202     if ((http_result == 200) && (ps->send_connected==GNUNET_YES))
1203     {
1204       ps->send_connected = GNUNET_NO;
1205       ps->send_active = GNUNET_NO;
1206 #if DEBUG_CONNECTIONS
1207       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: sending disconnected\n",ps);
1208 #endif
1209     }
1210   }
1211
1212   tmp = NULL;
1213   if ((size * nmemb) < SIZE_MAX)
1214     tmp = GNUNET_malloc (len+1);
1215
1216   if ((tmp != NULL) && (len > 0))
1217   {
1218     memcpy(tmp,ptr,len);
1219     if (len>=2)
1220     {
1221       if (tmp[len-2] == 13)
1222         tmp[len-2]= '\0';
1223     }
1224   }
1225   if (NULL != tmp)
1226     GNUNET_free (tmp);
1227
1228   return size * nmemb;
1229 }
1230
1231 /**
1232  * Callback method used with libcurl
1233  * Method is called when libcurl needs to read data during sending
1234  * @param stream pointer where to write data
1235  * @param size size of an individual element
1236  * @param nmemb count of elements that can be written to the buffer
1237  * @param ptr source pointer, passed to the libcurl handle
1238  * @return bytes written to stream
1239  */
1240 static size_t curl_send_cb(void *stream, size_t size, size_t nmemb, void *ptr)
1241 {
1242   struct Session * ps = ptr;
1243   struct HTTP_Message * msg = ps->pending_msgs_tail;
1244   size_t bytes_sent;
1245   size_t len;
1246
1247   if (ps->send_active == GNUNET_NO)
1248         return CURL_READFUNC_PAUSE;
1249
1250
1251   if ((ps->pending_msgs_tail == NULL) && (ps->send_active == GNUNET_YES))
1252   {
1253 #if DEBUG_CONNECTIONS
1254     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: No Message to send, pausing connection\n",ps);
1255 #endif
1256     ps->send_active = GNUNET_NO;
1257     return CURL_READFUNC_PAUSE;
1258   }
1259
1260   msg = ps->pending_msgs_tail;
1261   /* data to send */
1262   if (msg->pos < msg->size)
1263   {
1264     /* data fit in buffer */
1265     if ((msg->size - msg->pos) <= (size * nmemb))
1266     {
1267       len = (msg->size - msg->pos);
1268       memcpy(stream, &msg->buf[msg->pos], len);
1269       msg->pos += len;
1270       bytes_sent = len;
1271     }
1272     else
1273     {
1274       len = size*nmemb;
1275       memcpy(stream, &msg->buf[msg->pos], len);
1276       msg->pos += len;
1277       bytes_sent = len;
1278     }
1279   }
1280   /* no data to send */
1281   else
1282   {
1283     bytes_sent = 0;
1284   }
1285
1286   if ( msg->pos == msg->size)
1287   {
1288 #if DEBUG_CONNECTIONS
1289     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: Message with %u bytes sent, removing message from queue \n",ps, msg->pos);
1290 #endif
1291     /* Calling transmit continuation  */
1292     if (( NULL != ps->pending_msgs_tail) && (NULL != ps->pending_msgs_tail->transmit_cont))
1293       msg->transmit_cont (ps->pending_msgs_tail->transmit_cont_cls,&(ps->peercontext)->identity,GNUNET_OK);
1294     remove_http_message(ps, msg);
1295   }
1296   return bytes_sent;
1297 }
1298
1299 static void curl_receive_mst_cb  (void *cls,
1300                                 void *client,
1301                                 const struct GNUNET_MessageHeader *message)
1302 {
1303   struct Session *ps  = cls;
1304   struct HTTP_PeerContext *pc = ps->peercontext;
1305   GNUNET_assert(ps != NULL);
1306   GNUNET_assert(pc != NULL);
1307 #if DEBUG_HTTP
1308   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1309               "Connection %X: Forwarding message to transport service, type %u and size %u from `%s' (`%s')\n",
1310               ps,
1311               ntohs(message->type),
1312               ntohs(message->size),
1313               GNUNET_i2s(&(pc->identity)),http_plugin_address_to_string(NULL,ps->addr,ps->addrlen));
1314 #endif
1315   pc->plugin->env->receive (pc->plugin->env->cls,
1316                             &pc->identity,
1317                             message, 1, ps,
1318                             ps->addr,
1319                             ps->addrlen);
1320 }
1321
1322
1323 /**
1324 * Callback method used with libcurl
1325 * Method is called when libcurl needs to write data during sending
1326 * @param stream pointer where to write data
1327 * @param size size of an individual element
1328 * @param nmemb count of elements that can be written to the buffer
1329 * @param ptr destination pointer, passed to the libcurl handle
1330 * @return bytes read from stream
1331 */
1332 static size_t curl_receive_cb( void *stream, size_t size, size_t nmemb, void *ptr)
1333 {
1334   struct Session * ps = ptr;
1335 #if DEBUG_CONNECTIONS
1336   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: %u bytes received\n",ps, size*nmemb);
1337 #endif
1338   GNUNET_SERVER_mst_receive(ps->msgtok, ps, stream, size*nmemb, GNUNET_NO, GNUNET_NO);
1339   return (size * nmemb);
1340
1341 }
1342
1343 static void curl_perform (void *cls,
1344              const struct GNUNET_SCHEDULER_TaskContext *tc)
1345 {
1346   struct Plugin *plugin = cls;
1347   static unsigned int handles_last_run;
1348   int running;
1349   struct CURLMsg *msg;
1350   CURLMcode mret;
1351   struct Session *ps = NULL;
1352   struct HTTP_PeerContext *pc = NULL;
1353   struct HTTP_Message * cur_msg = NULL;
1354   long http_result;
1355   char * tmp;
1356
1357   GNUNET_assert(cls !=NULL);
1358
1359   plugin->http_curl_task = GNUNET_SCHEDULER_NO_TASK;
1360   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1361     return;
1362
1363   do
1364     {
1365       running = 0;
1366       mret = curl_multi_perform (plugin->multi_handle, &running);
1367       if ((running < handles_last_run) && (running>0))
1368         {
1369           do
1370             {
1371
1372               msg = curl_multi_info_read (plugin->multi_handle, &running);
1373               if (running == 0)
1374                   break;
1375               /* get session for affected curl handle */
1376               GNUNET_assert ( msg->easy_handle != NULL );
1377               curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, &tmp);
1378               ps = (struct Session *) tmp;
1379               GNUNET_assert ( ps != NULL );
1380               pc = ps->peercontext;
1381               GNUNET_assert ( pc != NULL );
1382               switch (msg->msg)
1383                 {
1384
1385                 case CURLMSG_DONE:
1386                   if ( (msg->data.result != CURLE_OK) &&
1387                        (msg->data.result != CURLE_GOT_NOTHING) )
1388                   {
1389                     /* sending msg failed*/
1390                     if (msg->easy_handle == ps->send_endpoint)
1391                     {
1392 #if DEBUG_CONNECTIONS
1393                       GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1394                                  _("Connection %X: HTTP PUT to peer `%s' (`%s') failed: `%s' `%s'\n"),
1395                                  ps,
1396                                  GNUNET_i2s(&pc->identity),
1397                                  http_plugin_address_to_string(NULL, ps->addr, ps->addrlen),
1398                                  "curl_multi_perform",
1399                                  curl_easy_strerror (msg->data.result));
1400 #endif
1401                       ps->send_connected = GNUNET_NO;
1402                       ps->send_active = GNUNET_NO;
1403                       curl_multi_remove_handle(plugin->multi_handle,ps->send_endpoint);
1404                       //curl_easy_cleanup(ps->send_endpoint);
1405                       //ps->send_endpoint=NULL;
1406                       cur_msg = ps->pending_msgs_tail;
1407                       if (( NULL != cur_msg) && ( NULL != cur_msg->transmit_cont))
1408                         cur_msg->transmit_cont (cur_msg->transmit_cont_cls,&pc->identity,GNUNET_SYSERR);
1409                     }
1410                     /* GET connection failed */
1411                     if (msg->easy_handle == ps->recv_endpoint)
1412                     {
1413 #if DEBUG_CONNECTIONS
1414                       GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1415                            _("Connection %X: HTTP GET to peer `%s' (`%s') failed: `%s' `%s'\n"),
1416                            ps,
1417                            GNUNET_i2s(&pc->identity),
1418                            http_plugin_address_to_string(NULL, ps->addr, ps->addrlen),
1419                            "curl_multi_perform",
1420                            curl_easy_strerror (msg->data.result));
1421 #endif
1422                       ps->recv_connected = GNUNET_NO;
1423                       ps->recv_active = GNUNET_NO;
1424                       curl_multi_remove_handle(plugin->multi_handle,ps->recv_endpoint);
1425                       //curl_easy_cleanup(ps->recv_endpoint);
1426                       //ps->recv_endpoint=NULL;
1427                     }
1428                   }
1429                   else
1430                   {
1431                     if (msg->easy_handle == ps->send_endpoint)
1432                     {
1433                       GNUNET_assert (CURLE_OK == curl_easy_getinfo(msg->easy_handle, CURLINFO_RESPONSE_CODE, &http_result));
1434 #if DEBUG_CONNECTIONS
1435                       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1436                                   "Connection %X: HTTP PUT connection to peer `%s' (`%s') was closed with HTTP code %u\n",
1437                                    ps,
1438                                    GNUNET_i2s(&pc->identity),
1439                                    http_plugin_address_to_string(NULL, ps->addr, ps->addrlen),
1440                                    http_result);
1441 #endif
1442                       /* Calling transmit continuation  */
1443                       cur_msg = ps->pending_msgs_tail;
1444                       if (( NULL != cur_msg) && (NULL != cur_msg->transmit_cont))
1445                       {
1446                         /* HTTP 1xx : Last message before here was informational */
1447                         if ((http_result >=100) && (http_result < 200))
1448                           cur_msg->transmit_cont (cur_msg->transmit_cont_cls,&pc->identity,GNUNET_OK);
1449                         /* HTTP 2xx: successful operations */
1450                         if ((http_result >=200) && (http_result < 300))
1451                           cur_msg->transmit_cont (cur_msg->transmit_cont_cls,&pc->identity,GNUNET_OK);
1452                         /* HTTP 3xx..5xx: error */
1453                         if ((http_result >=300) && (http_result < 600))
1454                           cur_msg->transmit_cont (cur_msg->transmit_cont_cls,&pc->identity,GNUNET_SYSERR);
1455                       }
1456                       ps->send_connected = GNUNET_NO;
1457                       ps->send_active = GNUNET_NO;
1458                       curl_multi_remove_handle(plugin->multi_handle,ps->send_endpoint);
1459                       //curl_easy_cleanup(ps->send_endpoint);
1460                       //ps->send_endpoint =NULL;
1461                     }
1462                     if (msg->easy_handle == ps->recv_endpoint)
1463                     {
1464 #if DEBUG_CONNECTIONS
1465                       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1466                                   "Connection %X: HTTP GET connection to peer `%s' (`%s') was closed with HTTP code %u\n",
1467                                    ps,
1468                                    GNUNET_i2s(&pc->identity),
1469                                    http_plugin_address_to_string(NULL, ps->addr, ps->addrlen),
1470                                    http_result);
1471 #endif
1472                       ps->recv_connected = GNUNET_NO;
1473                       ps->recv_active = GNUNET_NO;
1474                       curl_multi_remove_handle(plugin->multi_handle,ps->recv_endpoint);
1475                       //curl_easy_cleanup(ps->recv_endpoint);
1476                       //ps->recv_endpoint=NULL;
1477                     }
1478                   }
1479                   if ((ps->recv_connected == GNUNET_NO) && (ps->send_connected == GNUNET_NO))
1480                     remove_session (pc, ps, GNUNET_YES, GNUNET_SYSERR);
1481                   break;
1482                 default:
1483                   break;
1484                 }
1485
1486             }
1487           while ( (running > 0) );
1488         }
1489       handles_last_run = running;
1490     }
1491   while (mret == CURLM_CALL_MULTI_PERFORM);
1492   curl_schedule(plugin);
1493 }
1494
1495
1496 /**
1497  * Function setting up file descriptors and scheduling task to run
1498  * @param ses session to send data to
1499  * @return GNUNET_SYSERR for hard failure, GNUNET_OK for ok
1500  */
1501 static int curl_schedule(void *cls)
1502 {
1503   struct Plugin *plugin = cls;
1504   fd_set rs;
1505   fd_set ws;
1506   fd_set es;
1507   int max;
1508   struct GNUNET_NETWORK_FDSet *grs;
1509   struct GNUNET_NETWORK_FDSet *gws;
1510   long to;
1511   CURLMcode mret;
1512
1513   GNUNET_assert(cls !=NULL);
1514
1515   /* Cancel previous scheduled task */
1516   if (plugin->http_curl_task !=  GNUNET_SCHEDULER_NO_TASK)
1517   {
1518           GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_curl_task);
1519           plugin->http_curl_task = GNUNET_SCHEDULER_NO_TASK;
1520   }
1521   max = -1;
1522   FD_ZERO (&rs);
1523   FD_ZERO (&ws);
1524   FD_ZERO (&es);
1525   mret = curl_multi_fdset (plugin->multi_handle, &rs, &ws, &es, &max);
1526   if (mret != CURLM_OK)
1527     {
1528       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1529                   _("%s failed at %s:%d: `%s'\n"),
1530                   "curl_multi_fdset", __FILE__, __LINE__,
1531                   curl_multi_strerror (mret));
1532       return GNUNET_SYSERR;
1533     }
1534   mret = curl_multi_timeout (plugin->multi_handle, &to);
1535   if (mret != CURLM_OK)
1536     {
1537       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1538                   _("%s failed at %s:%d: `%s'\n"),
1539                   "curl_multi_timeout", __FILE__, __LINE__,
1540                   curl_multi_strerror (mret));
1541       return GNUNET_SYSERR;
1542     }
1543
1544   grs = GNUNET_NETWORK_fdset_create ();
1545   gws = GNUNET_NETWORK_fdset_create ();
1546   GNUNET_NETWORK_fdset_copy_native (grs, &rs, max + 1);
1547   GNUNET_NETWORK_fdset_copy_native (gws, &ws, max + 1);
1548   plugin->http_curl_task = GNUNET_SCHEDULER_add_select (plugin->env->sched,
1549                                    GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1550                                    GNUNET_SCHEDULER_NO_TASK,
1551                                    GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 0),
1552                                    grs,
1553                                    gws,
1554                                    &curl_perform,
1555                                    plugin);
1556   GNUNET_NETWORK_fdset_destroy (gws);
1557   GNUNET_NETWORK_fdset_destroy (grs);
1558   return GNUNET_OK;
1559 }
1560
1561 /**
1562  * Function setting up curl handle and selecting message to send
1563  * @param cls plugin
1564  * @param ses session to send data to
1565  * @param con connection
1566  * @return GNUNET_SYSERR on failure, GNUNET_NO if connecting, GNUNET_YES if ok
1567  */
1568 static ssize_t send_check_connections (void *cls, struct Session *ps)
1569 {
1570   struct Plugin *plugin = cls;
1571   CURLMcode mret;
1572   struct HTTP_Message * msg;
1573
1574   struct GNUNET_TIME_Relative timeout = GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT;
1575
1576   GNUNET_assert(cls !=NULL);
1577
1578   if (ps->direction == OUTBOUND)
1579   {
1580     /* RECV DIRECTION */
1581     /* Check if session is connected to receive data, otherwise connect to peer */
1582     if (ps->recv_connected == GNUNET_NO)
1583     {
1584         int fresh = GNUNET_NO;
1585         if (ps->recv_endpoint == NULL)
1586         {
1587             fresh = GNUNET_YES;
1588                 ps->recv_endpoint = curl_easy_init();
1589         }
1590 #if DEBUG_CURL
1591         curl_easy_setopt(ps->recv_endpoint, CURLOPT_VERBOSE, 1L);
1592 #endif
1593         curl_easy_setopt(ps->recv_endpoint, CURLOPT_URL, ps->url);
1594         curl_easy_setopt(ps->recv_endpoint, CURLOPT_HEADERFUNCTION, &curl_get_header_cb);
1595         curl_easy_setopt(ps->recv_endpoint, CURLOPT_WRITEHEADER, ps);
1596         curl_easy_setopt(ps->recv_endpoint, CURLOPT_READFUNCTION, curl_send_cb);
1597         curl_easy_setopt(ps->recv_endpoint, CURLOPT_READDATA, ps);
1598         curl_easy_setopt(ps->recv_endpoint, CURLOPT_WRITEFUNCTION, curl_receive_cb);
1599         curl_easy_setopt(ps->recv_endpoint, CURLOPT_WRITEDATA, ps);
1600         curl_easy_setopt(ps->recv_endpoint, CURLOPT_TIMEOUT, (long) timeout.value);
1601         curl_easy_setopt(ps->recv_endpoint, CURLOPT_PRIVATE, ps);
1602         curl_easy_setopt(ps->recv_endpoint, CURLOPT_CONNECTTIMEOUT, HTTP_CONNECT_TIMEOUT);
1603         curl_easy_setopt(ps->recv_endpoint, CURLOPT_BUFFERSIZE, GNUNET_SERVER_MAX_MESSAGE_SIZE);
1604
1605         if (fresh==GNUNET_YES)
1606         {
1607                         mret = curl_multi_add_handle(plugin->multi_handle, ps->recv_endpoint);
1608                         if (mret != CURLM_OK)
1609                         {
1610                           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1611                                                   _("Connection: %X: %s failed at %s:%d: `%s'\n"),
1612                                                   ps,
1613                                                   "curl_multi_add_handle", __FILE__, __LINE__,
1614                                                   curl_multi_strerror (mret));
1615                           return GNUNET_SYSERR;
1616                         }
1617         }
1618         if (curl_schedule (plugin) == GNUNET_SYSERR)
1619         {
1620 #if DEBUG_CONNECTIONS
1621         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: could not schedule curl task\n",ps);
1622 #endif
1623                 return GNUNET_SYSERR;
1624         }
1625 #if DEBUG_CONNECTIONS
1626         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: inbound not connected, initiating connection\n",ps);
1627 #endif
1628     }
1629
1630     /* waiting for receive direction */
1631     if (ps->recv_connected==GNUNET_NO)
1632       return GNUNET_NO;
1633
1634     /* SEND DIRECTION */
1635     /* Check if session is connected to send data, otherwise connect to peer */
1636     if ((ps->send_connected == GNUNET_YES) && (ps->send_endpoint!= NULL))
1637     {
1638       if (ps->send_active == GNUNET_YES)
1639       {
1640 #if DEBUG_CONNECTIONS
1641         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: outbound active, enqueueing message\n",ps);
1642 #endif
1643         return GNUNET_YES;
1644       }
1645       if (ps->send_active == GNUNET_NO)
1646       {
1647 #if DEBUG_CONNECTIONS
1648         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: outbound paused, unpausing existing connection and enqueueing message\n",ps);
1649 #endif
1650         if (CURLE_OK == curl_easy_pause(ps->send_endpoint,CURLPAUSE_CONT))
1651         {
1652                         ps->send_active=GNUNET_YES;
1653                         return GNUNET_YES;
1654         }
1655         else
1656                 return GNUNET_SYSERR;
1657       }
1658     }
1659     /* not connected, initiate connection */
1660     if (ps->send_connected==GNUNET_NO)
1661     {
1662         int fresh = GNUNET_NO;
1663         if (NULL == ps->send_endpoint)
1664         {
1665                 ps->send_endpoint = curl_easy_init();
1666                 fresh = GNUNET_YES;
1667         }
1668                 GNUNET_assert (ps->send_endpoint != NULL);
1669                 GNUNET_assert (NULL != ps->pending_msgs_tail);
1670 #if DEBUG_CONNECTIONS
1671                 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: outbound not connected, initiating connection\n",ps);
1672 #endif
1673                 ps->send_active = GNUNET_NO;
1674                 msg = ps->pending_msgs_tail;
1675
1676 #if DEBUG_CURL
1677                 curl_easy_setopt(ps->send_endpoint, CURLOPT_VERBOSE, 1L);
1678 #endif
1679                 curl_easy_setopt(ps->send_endpoint, CURLOPT_URL, ps->url);
1680                 curl_easy_setopt(ps->send_endpoint, CURLOPT_PUT, 1L);
1681                 curl_easy_setopt(ps->send_endpoint, CURLOPT_HEADERFUNCTION, &curl_put_header_cb);
1682                 curl_easy_setopt(ps->send_endpoint, CURLOPT_WRITEHEADER, ps);
1683                 curl_easy_setopt(ps->send_endpoint, CURLOPT_READFUNCTION, curl_send_cb);
1684                 curl_easy_setopt(ps->send_endpoint, CURLOPT_READDATA, ps);
1685                 curl_easy_setopt(ps->send_endpoint, CURLOPT_WRITEFUNCTION, curl_receive_cb);
1686                 curl_easy_setopt(ps->send_endpoint, CURLOPT_READDATA, ps);
1687                 curl_easy_setopt(ps->send_endpoint, CURLOPT_TIMEOUT, (long) timeout.value);
1688                 curl_easy_setopt(ps->send_endpoint, CURLOPT_PRIVATE, ps);
1689                 curl_easy_setopt(ps->send_endpoint, CURLOPT_CONNECTTIMEOUT, HTTP_CONNECT_TIMEOUT);
1690                 curl_easy_setopt(ps->send_endpoint, CURLOPT_BUFFERSIZE, GNUNET_SERVER_MAX_MESSAGE_SIZE);
1691
1692                 if (fresh==GNUNET_YES)
1693                 {
1694                         mret = curl_multi_add_handle(plugin->multi_handle, ps->send_endpoint);
1695                         if (mret != CURLM_OK)
1696                         {
1697                           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1698                                                   _("Connection: %X: %s failed at %s:%d: `%s'\n"),
1699                                                   ps,
1700                                                   "curl_multi_add_handle", __FILE__, __LINE__,
1701                                                   curl_multi_strerror (mret));
1702                           return GNUNET_SYSERR;
1703                         }
1704                 }
1705     }
1706     if (curl_schedule (plugin) == GNUNET_SYSERR)
1707         return GNUNET_SYSERR;
1708     return GNUNET_YES;
1709   }
1710   if (ps->direction == INBOUND)
1711   {
1712     GNUNET_assert (NULL != ps->pending_msgs_tail);
1713     if ((ps->recv_connected==GNUNET_YES) && (ps->send_connected==GNUNET_YES) &&
1714         (ps->recv_force_disconnect==GNUNET_NO) && (ps->recv_force_disconnect==GNUNET_NO))
1715         return GNUNET_YES;
1716   }
1717   return GNUNET_SYSERR;
1718 }
1719
1720 static struct Session * send_select_session (void * cls, struct HTTP_PeerContext *pc, const void * addr, size_t addrlen, int force_address, struct Session * session)
1721 {
1722         struct Session * tmp = NULL;
1723         int addr_given = GNUNET_NO;
1724
1725         if ((addr!=NULL) && (addrlen>0))
1726                 addr_given = GNUNET_YES;
1727
1728         if (force_address == GNUNET_YES)
1729         {
1730                 /* check session given as argument */
1731                 if ((session != NULL) && (addr_given == GNUNET_YES))
1732                 {
1733                       if (0 == memcmp(session->addr, addr, addrlen))
1734                       {
1735                         /* connection can not be used, since it is disconnected */
1736                         if ((session->recv_force_disconnect==GNUNET_NO) && (session->send_force_disconnect==GNUNET_NO))
1737                         {
1738 #if DEBUG_SESSION_SELECTION
1739                                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Session %X selected: Using session passed by transport to send to forced address \n", session);
1740 #endif
1741                                 return session;
1742                         }
1743                       }
1744                 }
1745                 /* check last session used */
1746                 if ((pc->last_session != NULL)&& (addr_given == GNUNET_YES))
1747                 {
1748                       if (0 == memcmp(pc->last_session->addr, addr, addrlen))
1749                       {
1750                         /* connection can not be used, since it is disconnected */
1751                         if ((pc->last_session->recv_force_disconnect==GNUNET_NO) && (pc->last_session->send_force_disconnect==GNUNET_NO))
1752                         {
1753 #if DEBUG_SESSION_SELECTION
1754                                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Session %X selected: Using last session used to send to forced address \n", pc->last_session);
1755 #endif
1756                                 return pc->last_session;
1757                         }
1758                       }
1759                 }
1760                 /* find session in existing sessions */
1761                 tmp = pc->head;
1762                 while ((tmp!=NULL) && (addr_given == GNUNET_YES))
1763                 {
1764
1765                           if (0 == memcmp(tmp->addr, addr, addrlen))
1766                       {
1767                         /* connection can not be used, since it is disconnected */
1768                         if ((tmp->recv_force_disconnect==GNUNET_NO) && (tmp->send_force_disconnect==GNUNET_NO))
1769                         {
1770 #if DEBUG_SESSION_SELECTION
1771                                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Session %X selected: Using existing session to send to forced address \n", session);
1772 #endif
1773                                   return session;
1774                         }
1775
1776                       }
1777                           tmp=tmp->next;
1778                 }
1779                 /* no session to use */
1780                 return NULL;
1781         }
1782         if ((force_address == GNUNET_NO) || (force_address == GNUNET_SYSERR))
1783         {
1784                 /* check session given as argument */
1785                 if (session != NULL)
1786                 {
1787                         /* connection can not be used, since it is disconnected */
1788                         if ((session->recv_force_disconnect==GNUNET_NO) && (session->send_force_disconnect==GNUNET_NO))
1789                         {
1790 #if DEBUG_SESSION_SELECTION
1791                                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Session %X selected: Using session passed by transport to send not-forced address \n", session);
1792 #endif
1793                                   return session;
1794                         }
1795
1796                 }
1797                 /* check last session used */
1798                 if (pc->last_session != NULL)
1799                 {
1800                         /* connection can not be used, since it is disconnected */
1801                         if ((pc->last_session->recv_force_disconnect==GNUNET_NO) && (pc->last_session->send_force_disconnect==GNUNET_NO))
1802                         {
1803 #if DEBUG_SESSION_SELECTION
1804                                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Session %X selected: Using last session to send to not-forced address \n", pc->last_session);
1805 #endif
1806                                 return pc->last_session;
1807                         }
1808                 }
1809                 /* find session in existing sessions */
1810                 tmp = pc->head;
1811                 while (tmp!=NULL)
1812                 {
1813                         /* connection can not be used, since it is disconnected */
1814                         if ((tmp->recv_force_disconnect==GNUNET_NO) && (tmp->send_force_disconnect==GNUNET_NO))
1815                         {
1816 #if DEBUG_SESSION_SELECTION
1817                                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Session %X selected: Using existing session to send to not-forced address \n", tmp);
1818 #endif
1819                                 return tmp;
1820                         }
1821                         tmp=tmp->next;
1822                 }
1823                 return NULL;
1824         }
1825         return NULL;
1826 }
1827
1828 /**
1829  * Function that can be used by the transport service to transmit
1830  * a message using the plugin.   Note that in the case of a
1831  * peer disconnecting, the continuation MUST be called
1832  * prior to the disconnect notification itself.  This function
1833  * will be called with this peer's HELLO message to initiate
1834  * a fresh connection to another peer.
1835  *
1836  * @param cls closure
1837  * @param target who should receive this message
1838  * @param msgbuf the message to transmit
1839  * @param msgbuf_size number of bytes in 'msgbuf'
1840  * @param priority how important is the message (most plugins will
1841  *                 ignore message priority and just FIFO)
1842  * @param timeout how long to wait at most for the transmission (does not
1843  *                require plugins to discard the message after the timeout,
1844  *                just advisory for the desired delay; most plugins will ignore
1845  *                this as well)
1846  * @param session which session must be used (or NULL for "any")
1847  * @param addr the address to use (can be NULL if the plugin
1848  *                is "on its own" (i.e. re-use existing TCP connection))
1849  * @param addrlen length of the address in bytes
1850  * @param force_address GNUNET_YES if the plugin MUST use the given address,
1851  *                GNUNET_NO means the plugin may use any other address and
1852  *                GNUNET_SYSERR means that only reliable existing
1853  *                bi-directional connections should be used (regardless
1854  *                of address)
1855  * @param cont continuation to call once the message has
1856  *        been transmitted (or if the transport is ready
1857  *        for the next transmission call; or if the
1858  *        peer disconnected...); can be NULL
1859  * @param cont_cls closure for cont
1860  * @return number of bytes used (on the physical network, with overheads);
1861  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
1862  *         and does NOT mean that the message was not transmitted (DV)
1863  */
1864 static ssize_t
1865 http_plugin_send (void *cls,
1866                   const struct GNUNET_PeerIdentity *target,
1867                   const char *msgbuf,
1868                   size_t msgbuf_size,
1869                   unsigned int priority,
1870                   struct GNUNET_TIME_Relative to,
1871                   struct Session *session,
1872                   const void *addr,
1873                   size_t addrlen,
1874                   int force_address,
1875                   GNUNET_TRANSPORT_TransmitContinuation cont,
1876                   void *cont_cls)
1877 {
1878   struct Plugin *plugin = cls;
1879   struct HTTP_Message *msg;
1880   struct HTTP_PeerContext * pc;
1881   struct Session * ps = NULL;
1882
1883   GNUNET_assert(cls !=NULL);
1884
1885 #if DEBUG_HTTP
1886   char * force = GNUNET_malloc(40);
1887   if (force_address == GNUNET_YES)
1888     strcpy(force,"forced addr.");
1889   if (force_address == GNUNET_NO)
1890     strcpy(force,"any addr.");
1891   if (force_address == GNUNET_SYSERR)
1892     strcpy(force,"reliable bi-direc. address addr.");
1893
1894   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Transport tells me to send %u bytes to `%s' using %s (%s) and session: %X\n",
1895                                       msgbuf_size,
1896                                       GNUNET_i2s(target),
1897                                       force,
1898                                       http_plugin_address_to_string(NULL, addr, addrlen),
1899                                       session);
1900
1901   GNUNET_free(force);
1902 #endif
1903
1904   pc = GNUNET_CONTAINER_multihashmap_get (plugin->peers, &target->hashPubKey);
1905   /* Peer unknown */
1906   if (pc==NULL)
1907   {
1908     pc = GNUNET_malloc(sizeof (struct HTTP_PeerContext));
1909     pc->plugin = plugin;
1910     pc->session_id_counter=1;
1911     pc->last_session = NULL;
1912     memcpy(&pc->identity, target, sizeof(struct GNUNET_PeerIdentity));
1913     GNUNET_CONTAINER_multihashmap_put(plugin->peers, &pc->identity.hashPubKey, pc, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1914     GNUNET_STATISTICS_update (plugin->env->stats,
1915                             gettext_noop ("# HTTP peers active"),
1916                             1,
1917                             GNUNET_NO);
1918   }
1919
1920   ps = send_select_session (plugin, pc, addr, addrlen, force_address, session);
1921
1922   /* session not existing, but address forced -> creating new session */
1923   if (ps==NULL)
1924   {
1925     if ((addr!=NULL) && (addrlen!=0))
1926     {
1927       ps = GNUNET_malloc(sizeof (struct Session));
1928 #if DEBUG_SESSION_SELECTION
1929       if (force_address == GNUNET_YES)
1930         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"No existing connection & forced address: creating new session %X to peer %s\n", ps, GNUNET_i2s(target));
1931       if (force_address != GNUNET_YES)
1932         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"No existing connection: creating new session %X to peer %s\n", ps, GNUNET_i2s(target));
1933 #endif
1934       if ((addrlen!=0) && (addr!=NULL))
1935       {
1936       ps->addr = GNUNET_malloc(addrlen);
1937       memcpy(ps->addr,addr,addrlen);
1938       ps->addrlen = addrlen;
1939       }
1940       else
1941       {
1942         ps->addr = NULL;
1943         ps->addrlen = 0;
1944       }
1945       ps->direction=OUTBOUND;
1946       ps->recv_connected = GNUNET_NO;
1947       ps->recv_force_disconnect = GNUNET_NO;
1948       ps->send_connected = GNUNET_NO;
1949       ps->send_force_disconnect = GNUNET_NO;
1950       ps->pending_msgs_head = NULL;
1951       ps->pending_msgs_tail = NULL;
1952       ps->peercontext=pc;
1953       ps->session_id = pc->session_id_counter;
1954       pc->session_id_counter++;
1955       ps->url = create_url (plugin, ps->addr, ps->addrlen, ps->session_id);
1956       if (ps->msgtok == NULL)
1957         ps->msgtok = GNUNET_SERVER_mst_create (&curl_receive_mst_cb, ps);
1958       GNUNET_CONTAINER_DLL_insert(pc->head,pc->tail,ps);
1959 /* FIXME */
1960
1961       GNUNET_STATISTICS_update (plugin->env->stats,
1962                             gettext_noop ("# HTTP outbound sessions for peers active"),
1963                             1,
1964                             GNUNET_NO);
1965     }
1966     else
1967     {
1968 #if DEBUG_HTTP
1969       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));
1970 #endif
1971       return GNUNET_SYSERR;
1972     }
1973   }
1974
1975   /* create msg */
1976   msg = GNUNET_malloc (sizeof (struct HTTP_Message) + msgbuf_size);
1977   msg->next = NULL;
1978   msg->size = msgbuf_size;
1979   msg->pos = 0;
1980   msg->buf = (char *) &msg[1];
1981   msg->transmit_cont = cont;
1982   msg->transmit_cont_cls = cont_cls;
1983   memcpy (msg->buf,msgbuf, msgbuf_size);
1984   GNUNET_CONTAINER_DLL_insert(ps->pending_msgs_head,ps->pending_msgs_tail,msg);
1985
1986   if (send_check_connections (plugin, ps) != GNUNET_SYSERR)
1987   {
1988           if (force_address != GNUNET_YES)
1989                   pc->last_session = ps;
1990
1991           if (pc->last_session==NULL)
1992                   pc->last_session = ps;
1993           return msg->size;
1994   }
1995   else
1996           return GNUNET_SYSERR;
1997 }
1998
1999
2000
2001 /**
2002  * Function that can be used to force the plugin to disconnect
2003  * from the given peer and cancel all previous transmissions
2004  * (and their continuationc).
2005  *
2006  * @param cls closure
2007  * @param target peer from which to disconnect
2008  */
2009 static void
2010 http_plugin_disconnect (void *cls,
2011                             const struct GNUNET_PeerIdentity *target)
2012 {
2013
2014
2015   struct Plugin *plugin = cls;
2016   struct HTTP_PeerContext *pc = NULL;
2017   struct Session *ps = NULL;
2018   //struct Session *tmp = NULL;
2019
2020   pc = GNUNET_CONTAINER_multihashmap_get (plugin->peers, &target->hashPubKey);
2021   if (pc==NULL)
2022     return;
2023   ps = pc->head;
2024
2025   while (ps!=NULL)
2026   {
2027     /* Telling transport that session is getting disconnected */
2028     plugin->env->session_end(plugin, target, ps);
2029     if (ps->direction==OUTBOUND)
2030     {
2031       if (ps->send_endpoint!=NULL)
2032       {
2033         //GNUNET_assert(CURLM_OK == curl_multi_remove_handle(plugin->multi_handle,ps->send_endpoint));
2034         //curl_easy_cleanup(ps->send_endpoint);
2035         //ps->send_endpoint=NULL;
2036         ps->send_force_disconnect = GNUNET_YES;
2037       }
2038       if (ps->recv_endpoint!=NULL)
2039       {
2040        //GNUNET_assert(CURLM_OK == curl_multi_remove_handle(plugin->multi_handle,ps->recv_endpoint));
2041        //curl_easy_cleanup(ps->recv_endpoint);
2042        //ps->recv_endpoint=NULL;
2043        ps->recv_force_disconnect = GNUNET_YES;
2044       }
2045     }
2046
2047     if (ps->direction==INBOUND)
2048     {
2049       ps->recv_force_disconnect = GNUNET_YES;
2050       ps->send_force_disconnect = GNUNET_YES;
2051     }
2052
2053     while (ps->pending_msgs_head!=NULL)
2054     {
2055       remove_http_message(ps, ps->pending_msgs_head);
2056     }
2057     ps->recv_active = GNUNET_NO;
2058     ps->send_active = GNUNET_NO;
2059     ps=ps->next;
2060   }
2061 }
2062
2063
2064 /**
2065  * Convert the transports address to a nice, human-readable
2066  * format.
2067  *
2068  * @param cls closure
2069  * @param type name of the transport that generated the address
2070  * @param addr one of the addresses of the host, NULL for the last address
2071  *        the specific address format depends on the transport
2072  * @param addrlen length of the address
2073  * @param numeric should (IP) addresses be displayed in numeric form?
2074  * @param timeout after how long should we give up?
2075  * @param asc function to call on each string
2076  * @param asc_cls closure for asc
2077  */
2078 static void
2079 http_plugin_address_pretty_printer (void *cls,
2080                                         const char *type,
2081                                         const void *addr,
2082                                         size_t addrlen,
2083                                         int numeric,
2084                                         struct GNUNET_TIME_Relative timeout,
2085                                         GNUNET_TRANSPORT_AddressStringCallback
2086                                         asc, void *asc_cls)
2087 {
2088   const struct IPv4HttpAddress *t4;
2089   const struct IPv6HttpAddress *t6;
2090   struct sockaddr_in a4;
2091   struct sockaddr_in6 a6;
2092   char * address;
2093   char * ret;
2094   unsigned int port;
2095   unsigned int res;
2096
2097   GNUNET_assert(cls !=NULL);
2098   if (addrlen == sizeof (struct IPv6HttpAddress))
2099   {
2100     address = GNUNET_malloc (INET6_ADDRSTRLEN);
2101     t6 = addr;
2102     a6.sin6_addr = t6->ipv6_addr;
2103     inet_ntop(AF_INET6, &(a6.sin6_addr),address,INET6_ADDRSTRLEN);
2104     port = ntohs(t6->u6_port);
2105   }
2106   else if (addrlen == sizeof (struct IPv4HttpAddress))
2107   {
2108     address = GNUNET_malloc (INET_ADDRSTRLEN);
2109     t4 = addr;
2110     a4.sin_addr.s_addr =  t4->ipv4_addr;
2111     inet_ntop(AF_INET, &(a4.sin_addr),address,INET_ADDRSTRLEN);
2112     port = ntohs(t4->u_port);
2113   }
2114   else
2115   {
2116     /* invalid address */
2117     GNUNET_break_op (0);
2118     asc (asc_cls, NULL);
2119     return;
2120   }
2121   res = GNUNET_asprintf(&ret,"%s://%s:%u/", PROTOCOL_PREFIX, address, port);
2122   GNUNET_free (address);
2123   GNUNET_assert(res != 0);
2124   asc (asc_cls, ret);
2125   GNUNET_free_non_null (ret);
2126 }
2127
2128
2129
2130 /**
2131  * Another peer has suggested an address for this
2132  * peer and transport plugin.  Check that this could be a valid
2133  * address.  If so, consider adding it to the list
2134  * of addresses.
2135  *
2136  * @param cls closure
2137  * @param addr pointer to the address
2138  * @param addrlen length of addr
2139  * @return GNUNET_OK if this is a plausible address for this peer
2140  *         and transport
2141  */
2142 static int
2143 http_plugin_address_suggested (void *cls,
2144                                const void *addr, size_t addrlen)
2145 {
2146   struct Plugin *plugin = cls;
2147   struct IPv4HttpAddress *v4;
2148   struct IPv6HttpAddress *v6;
2149   unsigned int port;
2150
2151   GNUNET_assert(cls !=NULL);
2152   if ((addrlen != sizeof (struct IPv4HttpAddress)) &&
2153       (addrlen != sizeof (struct IPv6HttpAddress)))
2154     {
2155       return GNUNET_SYSERR;
2156     }
2157   if (addrlen == sizeof (struct IPv4HttpAddress))
2158     {
2159       v4 = (struct IPv4HttpAddress *) addr;
2160       /* Not skipping loopback
2161       if (INADDR_LOOPBACK == ntohl(v4->ipv4_addr))
2162       {
2163         return GNUNET_SYSERR;
2164       } */
2165       port = ntohs (v4->u_port);
2166       if (port != plugin->port_inbound)
2167       {
2168         return GNUNET_SYSERR;
2169       }
2170     }
2171   if (addrlen == sizeof (struct IPv6HttpAddress))
2172     {
2173       v6 = (struct IPv6HttpAddress *) addr;
2174       if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
2175         {
2176           return GNUNET_SYSERR;
2177         }
2178       port = ntohs (v6->u6_port);
2179       if (port != plugin->port_inbound)
2180       {
2181         return GNUNET_SYSERR;
2182       }
2183     }
2184
2185   return GNUNET_OK;
2186 }
2187
2188
2189 /**
2190  * Function called for a quick conversion of the binary address to
2191  * a numeric address.  Note that the caller must not free the
2192  * address and that the next call to this function is allowed
2193  * to override the address again.
2194  *
2195  * @param cls closure
2196  * @param addr binary address
2197  * @param addrlen length of the address
2198  * @return string representing the same address
2199  */
2200 static const char*
2201 http_plugin_address_to_string (void *cls,
2202                                    const void *addr,
2203                                    size_t addrlen)
2204 {
2205   const struct IPv4HttpAddress *t4;
2206   const struct IPv6HttpAddress *t6;
2207   struct sockaddr_in a4;
2208   struct sockaddr_in6 a6;
2209   char * address;
2210   char * ret;
2211   uint16_t port;
2212   unsigned int res;
2213
2214   if (addrlen == sizeof (struct IPv6HttpAddress))
2215     {
2216       address = GNUNET_malloc (INET6_ADDRSTRLEN);
2217       t6 = addr;
2218       a6.sin6_addr = t6->ipv6_addr;
2219       inet_ntop(AF_INET6, &(a6.sin6_addr),address,INET6_ADDRSTRLEN);
2220       port = ntohs(t6->u6_port);
2221     }
2222   else if (addrlen == sizeof (struct IPv4HttpAddress))
2223     {
2224       address = GNUNET_malloc (INET_ADDRSTRLEN);
2225       t4 = addr;
2226       a4.sin_addr.s_addr =  t4->ipv4_addr;
2227       inet_ntop(AF_INET, &(a4.sin_addr),address,INET_ADDRSTRLEN);
2228       port = ntohs(t4->u_port);
2229     }
2230   else
2231     {
2232       /* invalid address */
2233       return NULL;
2234     }
2235   res = GNUNET_asprintf(&ret,"%s:%u",address,port);
2236   GNUNET_free (address);
2237   GNUNET_assert(res != 0);
2238   return ret;
2239 }
2240
2241
2242 /**
2243  * Exit point from the plugin.
2244  */
2245 void *
2246 libgnunet_plugin_transport_http_done (void *cls)
2247 {
2248   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2249   struct Plugin *plugin = api->cls;
2250   CURLMcode mret;
2251   GNUNET_assert(cls !=NULL);
2252
2253   if (plugin->http_server_daemon_v4 != NULL)
2254   {
2255     MHD_stop_daemon (plugin->http_server_daemon_v4);
2256     plugin->http_server_daemon_v4 = NULL;
2257   }
2258   if (plugin->http_server_daemon_v6 != NULL)
2259   {
2260     MHD_stop_daemon (plugin->http_server_daemon_v6);
2261     plugin->http_server_daemon_v6 = NULL;
2262   }
2263
2264   if ( plugin->http_server_task_v4 != GNUNET_SCHEDULER_NO_TASK)
2265   {
2266     GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_server_task_v4);
2267     plugin->http_server_task_v4 = GNUNET_SCHEDULER_NO_TASK;
2268   }
2269
2270   if ( plugin->http_server_task_v6 != GNUNET_SCHEDULER_NO_TASK)
2271   {
2272     GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_server_task_v6);
2273     plugin->http_server_task_v6 = GNUNET_SCHEDULER_NO_TASK;
2274   }
2275
2276
2277   /* free all peer information */
2278   if (plugin->peers!=NULL)
2279   {
2280           GNUNET_CONTAINER_multihashmap_iterate (plugin->peers,
2281                                                                                          &remove_peer_context_Iterator,
2282                                                                                          plugin);
2283           GNUNET_CONTAINER_multihashmap_destroy (plugin->peers);
2284   }
2285   if (plugin->multi_handle!=NULL)
2286   {
2287           mret = curl_multi_cleanup(plugin->multi_handle);
2288 #if DEBUG_HTTP
2289           if ( CURLM_OK != mret)
2290                 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"curl multihandle clean up failed\n");
2291 #endif
2292           plugin->multi_handle = NULL;
2293   }
2294   curl_global_cleanup();
2295
2296   if ( plugin->http_curl_task != GNUNET_SCHEDULER_NO_TASK)
2297   {
2298     GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_curl_task);
2299     plugin->http_curl_task = GNUNET_SCHEDULER_NO_TASK;
2300   }
2301
2302   GNUNET_free_non_null (plugin->bind4_address);
2303   GNUNET_free_non_null (plugin->bind6_address);
2304   GNUNET_free_non_null(plugin->bind_hostname);
2305   GNUNET_free (plugin);
2306   GNUNET_free (api);
2307 #if DEBUG_HTTP
2308   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Unload http plugin complete...\n");
2309 #endif
2310   return NULL;
2311 }
2312
2313
2314 /**
2315  * Entry point for the plugin.
2316  */
2317 void *
2318 libgnunet_plugin_transport_http_init (void *cls)
2319 {
2320   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2321   struct Plugin *plugin;
2322   struct GNUNET_TRANSPORT_PluginFunctions *api;
2323   struct GNUNET_TIME_Relative gn_timeout;
2324   long long unsigned int port;
2325
2326   GNUNET_assert(cls !=NULL);
2327 #if DEBUG_HTTP
2328   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting http plugin...\n");
2329 #endif
2330
2331   plugin = GNUNET_malloc (sizeof (struct Plugin));
2332   plugin->stats = env->stats;
2333   plugin->env = env;
2334   plugin->peers = NULL;
2335   plugin->bind4_address = NULL;
2336   plugin->use_ipv6  = GNUNET_YES;
2337   plugin->use_ipv4  = GNUNET_YES;
2338
2339   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2340   api->cls = plugin;
2341   api->send = &http_plugin_send;
2342   api->disconnect = &http_plugin_disconnect;
2343   api->address_pretty_printer = &http_plugin_address_pretty_printer;
2344   api->check_address = &http_plugin_address_suggested;
2345   api->address_to_string = &http_plugin_address_to_string;
2346
2347   /* Hashing our identity to use it in URLs */
2348   GNUNET_CRYPTO_hash_to_enc ( &(plugin->env->my_identity->hashPubKey), &plugin->my_ascii_hash_ident);
2349
2350   /* Reading port number from config file */
2351   if (GNUNET_CONFIGURATION_have_value (env->cfg,
2352                                                                    "transport-http", "USE_IPv6"))
2353     {
2354           plugin->use_ipv6 = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2355                                                                                                            "transport-http",
2356                                                                                                            "USE_IPv6");
2357     }
2358   /* Reading port number from config file */
2359   if (GNUNET_CONFIGURATION_have_value (env->cfg,
2360                                                                    "transport-http", "USE_IPv4"))
2361     {
2362           plugin->use_ipv4 = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2363                                                                                                            "transport-http",
2364                                                                                                            "USE_IPv4");
2365     }
2366   /* Reading port number from config file */
2367   if ((GNUNET_OK !=
2368        GNUNET_CONFIGURATION_get_value_number (env->cfg,
2369                                               "transport-http",
2370                                               "PORT",
2371                                               &port)) ||
2372       (port > 65535) )
2373     {
2374       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2375                        "http",
2376                        _("Require valid port number for transport plugin `%s' in configuration!\n"),
2377                        "transport-http");
2378       libgnunet_plugin_transport_http_done (api);
2379       return NULL;
2380     }
2381
2382   /* Reading ipv4 addresse to bind to from config file */
2383   if ((plugin->use_ipv4==GNUNET_YES) && (GNUNET_CONFIGURATION_have_value (env->cfg,
2384                                                                    "transport-http", "BINDTO4")))
2385   {
2386           GNUNET_break (GNUNET_OK ==
2387                                         GNUNET_CONFIGURATION_get_value_string (env->cfg,
2388                                                                                                                    "transport-http",
2389                                                                                                                    "BINDTO4",
2390                                                                                                                    &plugin->bind_hostname));
2391           plugin->bind4_address = GNUNET_malloc(sizeof(struct sockaddr_in));
2392           plugin->bind4_address->sin_family = AF_INET;
2393           plugin->bind4_address->sin_port = htons (port);
2394
2395           if (inet_pton(AF_INET,plugin->bind_hostname, &plugin->bind4_address->sin_addr)<=0)
2396           {
2397                   GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2398                                                    "http",
2399                                                    _("Misconfigured address to bind to in configuration!\n"),
2400                                                    "transport-http");
2401                   GNUNET_free(plugin->bind4_address);
2402                   GNUNET_free(plugin->bind_hostname);
2403                   plugin->bind_hostname = NULL;
2404                   plugin->bind4_address = NULL;
2405           }
2406   }
2407
2408   /* Reading ipv4 addresse to bind to from config file */
2409   if ((plugin->use_ipv6==GNUNET_YES) && (GNUNET_CONFIGURATION_have_value (env->cfg,
2410                                                                    "transport-http", "BINDTO6")))
2411   {
2412           GNUNET_break (GNUNET_OK ==
2413                                         GNUNET_CONFIGURATION_get_value_string (env->cfg,
2414                                                                                                                    "transport-http",
2415                                                                                                                    "BINDTO6",
2416                                                                                                                    &plugin->bind_hostname));
2417
2418           plugin->bind6_address = GNUNET_malloc(sizeof(struct sockaddr_in6));
2419           plugin->bind6_address->sin6_family = AF_INET6;
2420           plugin->bind6_address->sin6_port = htons (port);
2421
2422       if (inet_pton(AF_INET6,plugin->bind_hostname, &plugin->bind6_address->sin6_addr)<=0)
2423           {
2424                   GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2425                                                    "http",
2426                                                    _("Misconfigured address to bind to in configuration!\n"),
2427                                                    "transport-http");
2428                   GNUNET_free(plugin->bind6_address);
2429                   GNUNET_free(plugin->bind_hostname);
2430                   plugin->bind_hostname = NULL;
2431                   plugin->bind6_address = NULL;
2432           }
2433   }
2434
2435   GNUNET_assert ((port > 0) && (port <= 65535));
2436   plugin->port_inbound = port;
2437   gn_timeout = GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT;
2438   unsigned int timeout = (gn_timeout.value) / 1000;
2439   if ((plugin->http_server_daemon_v6 == NULL) && (plugin->use_ipv6 == GNUNET_YES) && (port != 0))
2440   {
2441         struct sockaddr * tmp = (struct sockaddr *) plugin->bind6_address;
2442     plugin->http_server_daemon_v6 = MHD_start_daemon (
2443 #if DEBUG_CONNECTIONS
2444                                                                    MHD_USE_DEBUG |
2445 #endif
2446                                                                    MHD_USE_IPv6,
2447                                        port,
2448                                        &mhd_accept_cb,
2449                                        plugin , &mdh_access_cb, plugin,
2450                                        MHD_OPTION_SOCK_ADDR, tmp,
2451                                        MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 32,
2452                                        //MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 6,
2453                                        MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) timeout,
2454                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
2455                                        MHD_OPTION_NOTIFY_COMPLETED, &mhd_termination_cb, NULL,
2456                                        MHD_OPTION_END);
2457   }
2458   if ((plugin->http_server_daemon_v4 == NULL) && (plugin->use_ipv4 == GNUNET_YES) && (port != 0))
2459   {
2460   plugin->http_server_daemon_v4 = MHD_start_daemon (
2461 #if DEBUG_CONNECTIONS
2462                                                                    MHD_USE_DEBUG |
2463 #endif
2464                                                                    MHD_NO_FLAG,
2465                                        port,
2466                                        &mhd_accept_cb,
2467                                        plugin , &mdh_access_cb, plugin,
2468                                        MHD_OPTION_SOCK_ADDR, (struct sockaddr_in *)plugin->bind4_address,
2469                                        MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 32,
2470                                        //MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 6,
2471                                        MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) timeout,
2472                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
2473                                        MHD_OPTION_NOTIFY_COMPLETED, &mhd_termination_cb, NULL,
2474                                        MHD_OPTION_END);
2475   }
2476   if (plugin->http_server_daemon_v4 != NULL)
2477     plugin->http_server_task_v4 = http_server_daemon_prepare (plugin, plugin->http_server_daemon_v4);
2478   if (plugin->http_server_daemon_v6 != NULL)
2479     plugin->http_server_task_v6 = http_server_daemon_prepare (plugin, plugin->http_server_daemon_v6);
2480
2481
2482   if (plugin->http_server_task_v4 != GNUNET_SCHEDULER_NO_TASK)
2483   {
2484 #if DEBUG_HTTP
2485           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);
2486 #endif
2487   }
2488   else if ((plugin->http_server_task_v6 != GNUNET_SCHEDULER_NO_TASK) && (plugin->http_server_task_v4 != GNUNET_SCHEDULER_NO_TASK))
2489   {
2490 #if DEBUG_HTTP
2491     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);
2492 #endif
2493   }
2494   else if ((plugin->http_server_task_v6 != GNUNET_SCHEDULER_NO_TASK) && (plugin->http_server_task_v4 == GNUNET_SCHEDULER_NO_TASK))
2495   {
2496 #if DEBUG_HTTP
2497     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);
2498 #endif
2499   }
2500   else
2501   {
2502 #if DEBUG_HTTP
2503     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"No MHD was started, transport plugin not functional!\n");
2504 #endif
2505     libgnunet_plugin_transport_http_done (api);
2506     return NULL;
2507   }
2508
2509   /* Initializing cURL */
2510   curl_global_init(CURL_GLOBAL_ALL);
2511   plugin->multi_handle = curl_multi_init();
2512
2513   if ( NULL == plugin->multi_handle )
2514   {
2515     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2516                                    "http",
2517                                    _("Could not initialize curl multi handle, failed to start http plugin!\n"),
2518                                    "transport-http");
2519     libgnunet_plugin_transport_http_done (api);
2520     return NULL;
2521   }
2522
2523   plugin->peers = GNUNET_CONTAINER_multihashmap_create (10);
2524   GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
2525
2526   return api;
2527 }
2528
2529 /* end of plugin_transport_http.c */