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