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