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