4e172e55f6c1d0edc7a69dc7441c7df24b0268ef
[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_constants.h"
29 #include "gnunet_protocols.h"
30 #include "gnunet_connection_lib.h"
31 #include "gnunet_service_lib.h"
32 #include "gnunet_statistics_service.h"
33 #include "gnunet_transport_service.h"
34 #include "gnunet_resolver_service.h"
35 #include "gnunet_server_lib.h"
36 #include "gnunet_container_lib.h"
37 #include "plugin_transport.h"
38 #include "gnunet_os_lib.h"
39 #include "microhttpd.h"
40 #include <curl/curl.h>
41
42
43 #define DEBUG_CURL GNUNET_NO
44 #define DEBUG_HTTP GNUNET_NO
45 #define DEBUG_CONNECTIONS GNUNET_NO
46
47 #define INBOUND GNUNET_NO
48 #define OUTBOUND GNUNET_YES
49
50 /**
51  * Text of the response sent back after the last bytes of a PUT
52  * request have been received (just to formally obey the HTTP
53  * protocol).
54  */
55 #define HTTP_PUT_RESPONSE "Thank you!"
56
57 /**
58  * After how long do we expire an address that we
59  * learned from another peer if it is not reconfirmed
60  * by anyone?
61  */
62 #define LEARNED_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 6)
63
64 /**
65  * Page returned if request invalid
66  */
67 #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>"
68
69 /**
70  * Timeout for a http connect
71  */
72 #define HTTP_CONNECT_TIMEOUT 30
73
74 /**
75  * Network format for IPv4 addresses.
76  */
77 struct IPv4HttpAddress
78 {
79   /**
80    * IPv4 address, in network byte order.
81    */
82   uint32_t ipv4_addr GNUNET_PACKED;
83
84   /**
85    * Port number, in network byte order.
86    */
87   uint16_t u_port GNUNET_PACKED;
88
89 };
90
91
92 /**
93  * Network format for IPv6 addresses.
94  */
95 struct IPv6HttpAddress
96 {
97   /**
98    * IPv6 address.
99    */
100   struct in6_addr ipv6_addr GNUNET_PACKED;
101
102   /**
103    * Port number, in network byte order.
104    */
105   uint16_t u6_port GNUNET_PACKED;
106
107 };
108
109
110 /**
111  *  Message to send using http
112  */
113 struct HTTP_Message
114 {
115   /**
116    * next pointer for double linked list
117    */
118   struct HTTP_Message * next;
119
120   /**
121    * previous pointer for double linked list
122    */
123   struct HTTP_Message * prev;
124
125   /**
126    * buffer containing data to send
127    */
128   char *buf;
129
130   /**
131    * amount of data already sent
132    */
133   size_t pos;
134
135   /**
136    * buffer length
137    */
138   size_t size;
139
140   /**
141    * Continuation function to call once the transmission buffer
142    * has again space available.  NULL if there is no
143    * continuation to call.
144    */
145   GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
146
147   /**
148    * Closure for transmit_cont.
149    */
150   void *transmit_cont_cls;
151 };
152
153
154 struct HTTP_PeerContext
155 {
156   struct GNUNET_PeerIdentity identity;
157
158   /**
159    * Pointer to the global plugin struct.
160    */
161   struct Plugin *plugin;
162
163   struct Session * head;
164   struct Session * tail;
165 };
166
167
168 struct Session
169 {
170   /**
171    * API requirement.
172    */
173   struct SessionHeader header;
174
175   /**
176    * next session in linked list
177    */
178   struct Session * next;
179
180   /**
181    * previous session in linked list
182    */
183   struct Session * prev;
184
185   /**
186    * address of this session
187    */
188   void * addr;
189
190   /**
191    * address length
192    */
193   size_t addrlen;
194
195   /**
196    * target url
197    */
198   char * url;
199
200   /**
201    * Message queue for outbound messages
202    * head of queue
203    */
204   struct HTTP_Message * pending_msgs_head;
205
206   /**
207    * Message queue for outbound messages
208    * tail of queue
209    */
210   struct HTTP_Message * pending_msgs_tail;
211
212   /**
213    * partner peer this connection belongs to
214    */
215   struct HTTP_PeerContext * peercontext;
216
217   /**
218    * message stream tokenizer for incoming data
219    */
220   struct GNUNET_SERVER_MessageStreamTokenizer *msgtok;
221
222   /**
223    * session direction
224    * outbound: OUTBOUND (GNUNET_YES)
225    * inbound : INBOUND (GNUNET_NO)
226    */
227   unsigned int direction;
228
229   /**
230    * is session connected to send data?
231    */
232   unsigned int send_connected;
233
234   /**
235    * is send connection active?
236    */
237   unsigned int send_active;
238
239   /**
240    * is session connected to receive data?
241    */
242   unsigned int recv_connected;
243
244   /**
245    * is receive connection active?
246    */
247   unsigned int recv_active;
248
249   /**
250    * entity managing sending data
251    * outbound session: pointer to curl easy handle
252    */
253   void * send_endpoint;
254
255   /**
256    * entity managing recieving data
257    * outbound session: pointer to curl easy handle
258    */
259   void * recv_endpoint;
260 };
261
262 /**
263  * Encapsulation of all of the state of the plugin.
264  */
265 struct Plugin
266 {
267   /**
268    * Our environment.
269    */
270   struct GNUNET_TRANSPORT_PluginEnvironment *env;
271
272   unsigned int port_inbound;
273
274   struct GNUNET_CONTAINER_MultiHashMap *peers;
275
276   /**
277    * Daemon for listening for new IPv4 connections.
278    */
279   struct MHD_Daemon *http_server_daemon_v4;
280
281   /**
282    * Daemon for listening for new IPv6connections.
283    */
284   struct MHD_Daemon *http_server_daemon_v6;
285
286   /**
287    * Our primary task for http daemon handling IPv4 connections
288    */
289   GNUNET_SCHEDULER_TaskIdentifier http_server_task_v4;
290
291   /**
292    * Our primary task for http daemon handling IPv6 connections
293    */
294   GNUNET_SCHEDULER_TaskIdentifier http_server_task_v6;
295
296   /**
297    * The task sending data
298    */
299   GNUNET_SCHEDULER_TaskIdentifier http_server_task_send;
300
301   /**
302    * cURL Multihandle
303    */
304   CURLM * multi_handle;
305
306   /**
307    * Our ASCII encoded, hashed peer identity
308    * This string is used to distinguish between connections and is added to the urls
309    */
310   struct GNUNET_CRYPTO_HashAsciiEncoded my_ascii_hash_ident;
311 };
312
313
314 /**
315  * Function called for a quick conversion of the binary address to
316  * a numeric address.  Note that the caller must not free the
317  * address and that the next call to this function is allowed
318  * to override the address again.
319  *
320  * @param cls closure
321  * @param addr binary address
322  * @param addrlen length of the address
323  * @return string representing the same address
324  */
325 static const char*
326 http_plugin_address_to_string (void *cls,
327                                    const void *addr,
328                                    size_t addrlen);
329
330 static char * create_url(void * cls, const void * addr, size_t addrlen)
331 {
332   struct Plugin *plugin = cls;
333   char *url = NULL;
334
335   GNUNET_assert ((addr!=NULL) && (addrlen != 0));
336   GNUNET_asprintf(&url,
337                   "http://%s/%s",
338                   http_plugin_address_to_string(NULL, addr, addrlen),
339                   (char *) (&plugin->my_ascii_hash_ident));
340
341   return url;
342 }
343
344 /**
345  * Removes a message from the linked list of messages
346  * @param con connection to remove message from
347  * @param msg message to remove
348  * @return GNUNET_SYSERR if msg not found, GNUNET_OK on success
349  */
350
351 static int remove_http_message(struct Session * ps, struct HTTP_Message * msg)
352 {
353   GNUNET_CONTAINER_DLL_remove(ps->pending_msgs_head,ps->pending_msgs_tail,msg);
354   GNUNET_free(msg);
355   return GNUNET_OK;
356 }
357
358 static struct Session * get_Session (void * cls, struct HTTP_PeerContext *pc, const void * addr, size_t addr_len)
359 {
360   struct Session * cc = pc->head;
361   struct Session * con = NULL;
362   unsigned int count = 0;
363
364   GNUNET_assert((addr_len == sizeof (struct IPv4HttpAddress)) || (addr_len == sizeof (struct IPv6HttpAddress)));
365   while (cc!=NULL)
366   {
367     if (addr_len == cc->addrlen)
368     {
369       if (0 == memcmp(cc->addr, addr, addr_len))
370       {
371         con = cc;
372         break;
373       }
374     }
375     count++;
376     cc=cc->next;
377   }
378   return con;
379 }
380
381
382 /**
383  * Callback called by MHD when a connection is terminated
384  */
385 static void requestCompletedCallback (void *cls, struct MHD_Connection * connection, void **httpSessionCache)
386 {
387   struct Session * ps = *httpSessionCache;
388   if (ps == NULL)
389     return;
390 #if DEBUG_CONNECTIONS
391   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection from peer `%s' was terminated\n",GNUNET_i2s(&ps->peercontext->identity));
392 #endif
393   /* session set to inactive */
394   //ps-> = GNUNET_NO;
395   //con->is_bad_request = GNUNET_NO;
396 }
397
398 static void mhd_write_mst_cb (void *cls,
399                               void *client,
400                               const struct GNUNET_MessageHeader *message)
401 {
402
403   struct Session *ps  = cls;
404   struct HTTP_PeerContext *pc = ps->peercontext;
405   GNUNET_assert(ps != NULL);
406   GNUNET_assert(pc != NULL);
407
408   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
409               "Forwarding message to transport service, type %u and size %u from `%s' (`%s')\n",
410               ntohs(message->type),
411               ntohs(message->size),
412               GNUNET_i2s(&(ps->peercontext)->identity),http_plugin_address_to_string(NULL,ps->addr,ps->addrlen));
413
414   pc->plugin->env->receive (ps->peercontext->plugin->env->cls,
415                             &pc->identity,
416                             message, 1, ps,
417                             ps->addr,
418                             ps->addrlen);
419 }
420
421 static void curl_write_mst_cb  (void *cls,
422                                 void *client,
423                                 const struct GNUNET_MessageHeader *message)
424 {
425   struct Session *ps  = cls;
426   struct HTTP_PeerContext *pc = ps->peercontext;
427   GNUNET_assert(ps != NULL);
428   GNUNET_assert(pc != NULL);
429
430   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
431               "Forwarding message to transport service, type %u and size %u from `%s' (`%s')\n",
432               ntohs(message->type),
433               ntohs(message->size),
434               GNUNET_i2s(&(pc->identity)),http_plugin_address_to_string(NULL,ps->addr,ps->addrlen));
435
436   pc->plugin->env->receive (pc->plugin->env->cls,
437                             &pc->identity,
438                             message, 1, ps,
439                             ps->addr,
440                             ps->addrlen);
441 }
442
443
444 /**
445  * Check if ip is allowed to connect.
446  */
447 static int
448 acceptPolicyCallback (void *cls,
449                       const struct sockaddr *addr, socklen_t addr_len)
450 {
451 #if 0
452   struct Plugin *plugin = cls;
453 #endif
454   /* Every connection is accepted, nothing more to do here */
455   return MHD_YES;
456 }
457
458 int server_read_callback (void *cls, uint64_t pos, char *buf, int max)
459 {
460   int bytes_read = 0;
461
462   struct Session * ps = cls;
463   struct HTTP_PeerContext * pc;
464   struct HTTP_Message * msg;
465   int res;res=5;
466
467   GNUNET_assert (ps!=NULL);
468   pc = ps->peercontext;
469   msg = ps->pending_msgs_tail;
470
471   if (msg!=NULL)
472   {
473     if ((msg->size-msg->pos) <= max)
474       {
475         memcpy(buf,&msg->buf[pos],(msg->size-msg->pos));
476         pos+=(msg->size-msg->pos);
477       }
478       else
479       {
480         memcpy(buf,&msg->buf[pos],max);
481         pos+=max;
482       }
483
484       if (msg->pos==msg->size)
485       {
486         if (NULL!=msg->transmit_cont)
487           msg->transmit_cont (msg->transmit_cont_cls,&pc->identity,GNUNET_SYSERR);
488         res = remove_http_message(ps,msg);
489       }
490   }
491   return bytes_read;
492 }
493
494 /**
495  * Process GET or PUT request received via MHD.  For
496  * GET, queue response that will send back our pending
497  * messages.  For PUT, process incoming data and send
498  * to GNUnet core.  In either case, check if a session
499  * already exists and create a new one if not.
500  */
501 static int
502 accessHandlerCallback (void *cls,
503                        struct MHD_Connection *mhd_connection,
504                        const char *url,
505                        const char *method,
506                        const char *version,
507                        const char *upload_data,
508                        size_t * upload_data_size, void **httpSessionCache)
509 {
510   struct Plugin *plugin = cls;
511   struct MHD_Response *response;
512   const union MHD_ConnectionInfo * conn_info;
513
514   struct sockaddr_in  *addrin;
515   struct sockaddr_in6 *addrin6;
516
517   char address[INET6_ADDRSTRLEN+14];
518   struct GNUNET_PeerIdentity pi_in;
519
520   struct IPv4HttpAddress ipv4addr;
521   struct IPv6HttpAddress ipv6addr;
522
523   struct HTTP_PeerContext *pc;
524   struct Session *ps;
525
526   int res = GNUNET_NO;
527   int send_error_to_client;
528   void * addr;
529   size_t addr_len;
530
531   GNUNET_assert(cls !=NULL);
532   send_error_to_client = GNUNET_NO;
533
534   if (NULL == *httpSessionCache)
535   {
536     /* check url for peer identity , if invalid send HTTP 404*/
537     res = GNUNET_CRYPTO_hash_from_string ( &url[1], &(pi_in.hashPubKey));
538     if ( GNUNET_SYSERR == res )
539     {
540       response = MHD_create_response_from_data (strlen (HTTP_ERROR_RESPONSE),HTTP_ERROR_RESPONSE, MHD_NO, MHD_NO);
541       res = MHD_queue_response (mhd_connection, MHD_HTTP_NOT_FOUND, response);
542       MHD_destroy_response (response);
543       if (res == MHD_YES)
544         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Peer has no valid ident, sent HTTP 1.1/404\n");
545       else
546         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Peer has no valid ident, could not send error\n");
547       return res;
548     }
549   }
550   else
551   {
552     ps = *httpSessionCache;
553     pc = ps->peercontext;
554   }
555
556   if (NULL == *httpSessionCache)
557   {
558     /* get peer context */
559     pc = GNUNET_CONTAINER_multihashmap_get (plugin->peers, &pi_in.hashPubKey);
560     /* Peer unknown */
561     if (pc==NULL)
562     {
563       pc = GNUNET_malloc(sizeof (struct HTTP_PeerContext));
564       pc->plugin = plugin;
565       memcpy(&pc->identity, &pi_in, sizeof(struct GNUNET_PeerIdentity));
566       GNUNET_CONTAINER_multihashmap_put(plugin->peers, &pc->identity.hashPubKey, pc, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
567     }
568
569     conn_info = MHD_get_connection_info(mhd_connection, MHD_CONNECTION_INFO_CLIENT_ADDRESS );
570     /* Incoming IPv4 connection */
571     if ( AF_INET == conn_info->client_addr->sin_family)
572     {
573       addrin = conn_info->client_addr;
574       inet_ntop(addrin->sin_family, &(addrin->sin_addr),address,INET_ADDRSTRLEN);
575       memcpy(&ipv4addr.ipv4_addr,&(addrin->sin_addr),sizeof(struct in_addr));
576       ipv4addr.u_port = addrin->sin_port;
577       addr = &ipv4addr;
578       addr_len = sizeof(struct IPv4HttpAddress);
579       //con = session_check_inbound_address (plugin, cs, (const void *) &ipv4addr, sizeof (struct IPv4HttpAddress));
580     }
581     /* Incoming IPv6 connection */
582     if ( AF_INET6 == conn_info->client_addr->sin_family)
583     {
584       addrin6 = (struct sockaddr_in6 *) conn_info->client_addr;
585       inet_ntop(addrin6->sin6_family, &(addrin6->sin6_addr),address,INET6_ADDRSTRLEN);
586       memcpy(&ipv6addr.ipv6_addr,&(addrin6->sin6_addr),sizeof(struct in6_addr));
587       ipv6addr.u6_port = addrin6->sin6_port;
588       addr = &ipv6addr;
589       addr_len = sizeof(struct IPv6HttpAddress);
590     }
591     /* Set closure and update current session*/
592     ps = get_Session(plugin, pc, addr, addr_len);
593     if (ps==NULL)
594     {
595       ps = GNUNET_malloc(sizeof (struct Session));
596       ps->addr = GNUNET_malloc(addr_len);
597       memcpy(ps->addr,addr,addr_len);
598       ps->addrlen = addr_len;
599       ps->direction=INBOUND;
600       ps->pending_msgs_head = NULL;
601       ps->pending_msgs_tail = NULL;
602       ps->send_connected=GNUNET_NO;
603       ps->send_active=GNUNET_NO;
604       ps->recv_connected=GNUNET_NO;
605       ps->recv_active=GNUNET_NO;
606       ps->peercontext=pc;
607       ps->url = create_url (plugin, ps->addr, ps->addrlen);
608       GNUNET_CONTAINER_DLL_insert(pc->head,pc->tail,ps);
609     }
610
611     *httpSessionCache = ps;
612     if (ps->msgtok==NULL)
613       ps->msgtok = GNUNET_SERVER_mst_create (&mhd_write_mst_cb, ps);
614
615     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"HTTP Daemon has new an incoming `%s' request from peer `%s' (`%s')\n",
616                 method,
617                 GNUNET_i2s(&pc->identity),
618                 http_plugin_address_to_string(NULL, ps->addr, ps->addrlen));
619   }
620
621   /* Is it a PUT or a GET request */
622   if (0 == strcmp (MHD_HTTP_METHOD_PUT, method))
623   {
624     if ((*upload_data_size == 0) && (ps->recv_active==GNUNET_NO))
625     {
626       ps->recv_active = GNUNET_YES;
627       return MHD_YES;
628     }
629
630     /* Transmission of all data complete */
631     if ((*upload_data_size == 0) && (ps->recv_active == GNUNET_YES))
632     {
633       response = MHD_create_response_from_data (strlen (HTTP_PUT_RESPONSE),HTTP_PUT_RESPONSE, MHD_NO, MHD_NO);
634       res = MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
635 #if DEBUG_CONNECTIONS
636       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: Sent HTTP/1.1: 200 OK as PUT Response\n",ps);
637 #endif
638       MHD_destroy_response (response);
639       ps->recv_active=GNUNET_NO;
640       return MHD_YES;
641     }
642
643     /* Recieving data */
644     if ((*upload_data_size > 0) && (ps->recv_active == GNUNET_YES))
645     {
646       res = GNUNET_SERVER_mst_receive(ps->msgtok, ps, upload_data,*upload_data_size, GNUNET_NO, GNUNET_NO);
647       (*upload_data_size) = 0;
648       return MHD_YES;
649     }
650     else
651       return MHD_NO;
652   }
653   if ( 0 == strcmp (MHD_HTTP_METHOD_GET, method) )
654   {
655     response = MHD_create_response_from_callback(-1,32 * 1024, &server_read_callback, ps, NULL);
656     res = MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
657     MHD_destroy_response (response);
658     return res;
659   }
660   return MHD_NO;
661 }
662
663
664 /**
665  * Call MHD to process pending ipv4 requests and then go back
666  * and schedule the next run.
667  */
668 static void http_server_daemon_v4_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
669 /**
670  * Call MHD to process pending ipv6 requests and then go back
671  * and schedule the next run.
672  */
673 static void http_server_daemon_v6_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
674
675 /**
676  * Function that queries MHD's select sets and
677  * starts the task waiting for them.
678  */
679 static GNUNET_SCHEDULER_TaskIdentifier
680 http_server_daemon_prepare (void * cls, struct MHD_Daemon *daemon_handle)
681 {
682   struct Plugin *plugin = cls;
683   GNUNET_SCHEDULER_TaskIdentifier ret;
684   fd_set rs;
685   fd_set ws;
686   fd_set es;
687   struct GNUNET_NETWORK_FDSet *wrs;
688   struct GNUNET_NETWORK_FDSet *wws;
689   struct GNUNET_NETWORK_FDSet *wes;
690   int max;
691   unsigned long long timeout;
692   int haveto;
693   struct GNUNET_TIME_Relative tv;
694
695   GNUNET_assert(cls !=NULL);
696   ret = GNUNET_SCHEDULER_NO_TASK;
697   FD_ZERO(&rs);
698   FD_ZERO(&ws);
699   FD_ZERO(&es);
700   wrs = GNUNET_NETWORK_fdset_create ();
701   wes = GNUNET_NETWORK_fdset_create ();
702   wws = GNUNET_NETWORK_fdset_create ();
703   max = -1;
704   GNUNET_assert (MHD_YES ==
705                  MHD_get_fdset (daemon_handle,
706                                 &rs,
707                                 &ws,
708                                 &es,
709                                 &max));
710   haveto = MHD_get_timeout (daemon_handle, &timeout);
711   if (haveto == MHD_YES)
712     tv.value = (uint64_t) timeout;
713   else
714     tv = GNUNET_TIME_UNIT_FOREVER_REL;
715   GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max);
716   GNUNET_NETWORK_fdset_copy_native (wws, &ws, max);
717   GNUNET_NETWORK_fdset_copy_native (wes, &es, max);
718   if (daemon_handle == plugin->http_server_daemon_v4)
719   {
720     ret = GNUNET_SCHEDULER_add_select (plugin->env->sched,
721                                        GNUNET_SCHEDULER_PRIORITY_DEFAULT,
722                                        GNUNET_SCHEDULER_NO_TASK,
723                                        tv,
724                                        wrs,
725                                        wws,
726                                        &http_server_daemon_v4_run,
727                                        plugin);
728   }
729   if (daemon_handle == plugin->http_server_daemon_v6)
730   {
731     ret = GNUNET_SCHEDULER_add_select (plugin->env->sched,
732                                        GNUNET_SCHEDULER_PRIORITY_DEFAULT,
733                                        GNUNET_SCHEDULER_NO_TASK,
734                                        tv,
735                                        wrs,
736                                        wws,
737                                        &http_server_daemon_v6_run,
738                                        plugin);
739   }
740   GNUNET_NETWORK_fdset_destroy (wrs);
741   GNUNET_NETWORK_fdset_destroy (wws);
742   GNUNET_NETWORK_fdset_destroy (wes);
743   return ret;
744 }
745
746 /**
747  * Call MHD to process pending requests and then go back
748  * and schedule the next run.
749  */
750 static void http_server_daemon_v4_run (void *cls,
751                              const struct GNUNET_SCHEDULER_TaskContext *tc)
752 {
753   struct Plugin *plugin = cls;
754
755   GNUNET_assert(cls !=NULL);
756   if (plugin->http_server_task_v4 != GNUNET_SCHEDULER_NO_TASK)
757     plugin->http_server_task_v4 = GNUNET_SCHEDULER_NO_TASK;
758
759   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
760     return;
761
762   GNUNET_assert (MHD_YES == MHD_run (plugin->http_server_daemon_v4));
763   plugin->http_server_task_v4 = http_server_daemon_prepare (plugin, plugin->http_server_daemon_v4);
764   return;
765 }
766
767
768 /**
769  * Call MHD to process pending requests and then go back
770  * and schedule the next run.
771  */
772 static void http_server_daemon_v6_run (void *cls,
773                              const struct GNUNET_SCHEDULER_TaskContext *tc)
774 {
775   struct Plugin *plugin = cls;
776
777   GNUNET_assert(cls !=NULL);
778   if (plugin->http_server_task_v6 != GNUNET_SCHEDULER_NO_TASK)
779     plugin->http_server_task_v6 = GNUNET_SCHEDULER_NO_TASK;
780
781   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
782     return;
783
784   GNUNET_assert (MHD_YES == MHD_run (plugin->http_server_daemon_v6));
785   plugin->http_server_task_v6 = http_server_daemon_prepare (plugin, plugin->http_server_daemon_v6);
786   return;
787 }
788
789 /**
790  * Function setting up curl handle and selecting message to send
791  * @param cls plugin
792  * @param ses session to send data to
793  * @param con connection
794  * @return bytes sent to peer
795  */
796 static ssize_t send_check_connections (void *cls, struct Session* ses , struct Session *ps);
797
798
799 static size_t curl_get_header_function( void *ptr, size_t size, size_t nmemb, void *stream)
800 {
801   struct Session * ps = stream;
802
803   char * tmp;
804   size_t len = size * nmemb;
805   long http_result = 0;
806   int res;
807   /* Getting last http result code */
808   if (ps->recv_connected==GNUNET_NO)
809   {
810     GNUNET_assert(NULL!=ps);
811     res = curl_easy_getinfo(ps->recv_endpoint, CURLINFO_RESPONSE_CODE, &http_result);
812     if (CURLE_OK == res)
813     {
814       if (http_result == 200)
815       {
816         ps->recv_connected = GNUNET_YES;
817         ps->recv_active = GNUNET_YES;
818 #if DEBUG_CONNECTIONS
819         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: connected to recieve data\n",ps);
820 #endif
821         // Calling send_check_connections again since receive is established
822         send_check_connections (ps->peercontext->plugin, NULL, ps);
823       }
824     }
825   }
826
827   tmp = NULL;
828   if ((size * nmemb) < SIZE_MAX)
829     tmp = GNUNET_malloc (len+1);
830
831   if ((tmp != NULL) && (len > 0))
832   {
833     memcpy(tmp,ptr,len);
834     if (len>=2)
835     {
836       if (tmp[len-2] == 13)
837         tmp[len-2]= '\0';
838     }
839 #if DEBUG_HTTP
840     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Header: `%s' %u \n",tmp, http_result);
841 #endif
842   }
843   if (NULL != tmp)
844     GNUNET_free (tmp);
845
846   return size * nmemb;
847 }
848
849 static size_t curl_put_header_function( void *ptr, size_t size, size_t nmemb, void *stream)
850 {
851   struct Session * ps = stream;
852
853   char * tmp;
854   size_t len = size * nmemb;
855   long http_result = 0;
856   int res;
857
858   /* Getting last http result code */
859   GNUNET_assert(NULL!=ps);
860   res = curl_easy_getinfo(ps->send_endpoint, CURLINFO_RESPONSE_CODE, &http_result);
861   if (CURLE_OK == res)
862   {
863     if ((http_result == 100) && (ps->send_connected==GNUNET_NO))
864     {
865       ps->send_connected = GNUNET_YES;
866       ps->send_active = GNUNET_YES;
867 #if DEBUG_CONNECTIONS
868       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: connected to send data\n",ps);
869 #endif
870     }
871     if ((http_result == 200) && (ps->send_connected==GNUNET_YES))
872     {
873       ps->send_connected = GNUNET_NO;
874       ps->send_active = GNUNET_NO;
875 #if DEBUG_CONNECTIONS
876       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: sending disconnected\n",ps);
877 #endif
878     }
879   }
880
881   tmp = NULL;
882   if ((size * nmemb) < SIZE_MAX)
883     tmp = GNUNET_malloc (len+1);
884
885   if ((tmp != NULL) && (len > 0))
886   {
887     memcpy(tmp,ptr,len);
888     if (len>=2)
889     {
890       if (tmp[len-2] == 13)
891         tmp[len-2]= '\0';
892     }
893 #if DEBUG_HTTP
894     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Header: `%s' %u \n",tmp, http_result);
895 #endif
896   }
897   if (NULL != tmp)
898     GNUNET_free (tmp);
899
900   return size * nmemb;
901 }
902
903 /**
904  * Callback method used with libcurl
905  * Method is called when libcurl needs to read data during sending
906  * @param stream pointer where to write data
907  * @param size size of an individual element
908  * @param nmemb count of elements that can be written to the buffer
909  * @param ptr source pointer, passed to the libcurl handle
910  * @return bytes written to stream
911  */
912 static size_t send_curl_send_callback(void *stream, size_t size, size_t nmemb, void *ptr)
913 {
914   struct Session * ps = ptr;
915   struct HTTP_Message * msg = ps->pending_msgs_tail;
916   size_t bytes_sent;
917   size_t len;
918
919   if (ps->pending_msgs_tail == NULL)
920   {
921 #if DEBUG_CONNECTIONS
922     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: No Message to send, pausing connection\n",ps);
923 #endif
924     ps->send_active = GNUNET_NO;
925     return CURL_READFUNC_PAUSE;
926   }
927
928   msg = ps->pending_msgs_tail;
929   /* data to send */
930   if (msg->pos < msg->size)
931   {
932     /* data fit in buffer */
933     if ((msg->size - msg->pos) <= (size * nmemb))
934     {
935       len = (msg->size - msg->pos);
936       memcpy(stream, &msg->buf[msg->pos], len);
937       msg->pos += len;
938       bytes_sent = len;
939     }
940     else
941     {
942       len = size*nmemb;
943       memcpy(stream, &msg->buf[msg->pos], len);
944       msg->pos += len;
945       bytes_sent = len;
946     }
947   }
948   /* no data to send */
949   else
950   {
951     bytes_sent = 0;
952   }
953
954   if ( msg->pos == msg->size)
955   {
956 #if DEBUG_CONNECTIONS
957     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: Message with %u bytes sent, removing message from queue \n",ps, msg->pos);
958 #endif
959     /* Calling transmit continuation  */
960     if (( NULL != ps->pending_msgs_tail) && (NULL != ps->pending_msgs_tail->transmit_cont))
961       msg->transmit_cont (ps->pending_msgs_tail->transmit_cont_cls,&(ps->peercontext)->identity,GNUNET_OK);
962     remove_http_message(ps, msg);
963   }
964   return bytes_sent;
965 }
966
967 /**
968 * Callback method used with libcurl
969 * Method is called when libcurl needs to write data during sending
970 * @param stream pointer where to write data
971 * @param size size of an individual element
972 * @param nmemb count of elements that can be written to the buffer
973 * @param ptr destination pointer, passed to the libcurl handle
974 * @return bytes read from stream
975 */
976 static size_t send_curl_receive_callback( void *stream, size_t size, size_t nmemb, void *ptr)
977 {
978   struct Session * ps = ptr;
979 #if DEBUG_CONNECTIONS
980   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: %u bytes recieved\n",ps, size*nmemb);
981 #endif
982   GNUNET_SERVER_mst_receive(ps->msgtok, ps, stream, size*nmemb, GNUNET_NO, GNUNET_NO);
983
984   return (size * nmemb);
985
986 }
987
988 /**
989  * Function setting up file descriptors and scheduling task to run
990  * @param cls closure
991  * @param ses session to send data to
992  * @return bytes sent to peer
993  */
994 static size_t send_schedule(void *cls, struct Session* ses );
995
996
997
998 /**
999  * Function setting up curl handle and selecting message to send
1000  * @param cls plugin
1001  * @param ses session to send data to
1002  * @param con connection
1003  * @return bytes sent to peer
1004  */
1005 static ssize_t send_check_connections (void *cls, struct Session* ses , struct Session *ps)
1006 {
1007   struct Plugin *plugin = cls;
1008   int bytes_sent = 0;
1009   CURLMcode mret;
1010   struct HTTP_Message * msg;
1011   struct GNUNET_TIME_Relative timeout = GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT;
1012
1013   GNUNET_assert(cls !=NULL);
1014
1015   if (ps->direction == OUTBOUND)
1016   {
1017     /* RECV DIRECTION */
1018     /* Check if session is connected to receive data, otherwise connect to peer */
1019     if (ps->recv_connected == GNUNET_NO)
1020     {
1021         if (ps->recv_endpoint == NULL)
1022         {
1023           ps->recv_endpoint = curl_easy_init();
1024 #if DEBUG_CURL
1025         curl_easy_setopt(ps->recv_endpoint, CURLOPT_VERBOSE, 1L);
1026 #endif
1027         curl_easy_setopt(ps->recv_endpoint, CURLOPT_URL, ps->url);
1028         curl_easy_setopt(ps->recv_endpoint, CURLOPT_HEADERFUNCTION, &curl_get_header_function);
1029         curl_easy_setopt(ps->recv_endpoint, CURLOPT_WRITEHEADER, ps);
1030         curl_easy_setopt(ps->recv_endpoint, CURLOPT_READFUNCTION, send_curl_send_callback);
1031         curl_easy_setopt(ps->recv_endpoint, CURLOPT_READDATA, ps);
1032         curl_easy_setopt(ps->recv_endpoint, CURLOPT_WRITEFUNCTION, send_curl_receive_callback);
1033         curl_easy_setopt(ps->recv_endpoint, CURLOPT_WRITEDATA, ps);
1034         curl_easy_setopt(ps->recv_endpoint, CURLOPT_TIMEOUT, (long) timeout.value);
1035         curl_easy_setopt(ps->recv_endpoint, CURLOPT_PRIVATE, ps);
1036         curl_easy_setopt(ps->recv_endpoint, CURLOPT_CONNECTTIMEOUT, HTTP_CONNECT_TIMEOUT);
1037         curl_easy_setopt(ps->recv_endpoint, CURLOPT_BUFFERSIZE, GNUNET_SERVER_MAX_MESSAGE_SIZE);
1038
1039         mret = curl_multi_add_handle(plugin->multi_handle, ps->recv_endpoint);
1040         if (mret != CURLM_OK)
1041         {
1042           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1043                       _("%s failed at %s:%d: `%s'\n"),
1044                       "curl_multi_add_handle", __FILE__, __LINE__,
1045                       curl_multi_strerror (mret));
1046           return -1;
1047         }
1048         bytes_sent = send_schedule (plugin, NULL);
1049         if (ps->msgtok != NULL)
1050           ps->msgtok = GNUNET_SERVER_mst_create (&curl_write_mst_cb, ps);
1051 #if DEBUG_CONNECTIONS
1052         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: inbound not connected, initiating connection\n",ps);
1053 #endif
1054       }
1055     }
1056
1057     /* waiting for receive direction */
1058     if (ps->recv_connected==GNUNET_NO)
1059       return 0;
1060
1061     /* SEND DIRECTION */
1062     /* Check if session is connected to send data, otherwise connect to peer */
1063     if ((ps->send_connected == GNUNET_YES) && (ps->send_endpoint!= NULL))
1064     {
1065       if (ps->send_active == GNUNET_YES)
1066       {
1067 #if DEBUG_CONNECTIONS
1068         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: outbound active, enqueueing message\n",ps);
1069 #endif
1070         return bytes_sent;
1071       }
1072       if (ps->send_active == GNUNET_NO)
1073       {
1074 #if DEBUG_CONNECTIONS
1075         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: outbound paused, unpausing existing connection and enqueueing message\n",ps);
1076 #endif
1077         curl_easy_pause(ps->send_endpoint,CURLPAUSE_CONT);
1078         ps->send_active=GNUNET_YES;
1079         return bytes_sent;
1080       }
1081     }
1082     /* not connected, initiate connection */
1083     if ((ps->send_connected==GNUNET_NO) && (NULL == ps->send_endpoint))
1084       ps->send_endpoint = curl_easy_init();
1085     GNUNET_assert (ps->send_endpoint != NULL);
1086     GNUNET_assert (NULL != ps->pending_msgs_tail);
1087 #if DEBUG_CONNECTIONS
1088     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: outbound not connected, initiating connection\n",ps);
1089 #endif
1090     ps->send_active = GNUNET_NO;
1091     msg = ps->pending_msgs_tail;
1092
1093   #if DEBUG_CURL
1094     curl_easy_setopt(ps->send_endpoint, CURLOPT_VERBOSE, 1L);
1095   #endif
1096     curl_easy_setopt(ps->send_endpoint, CURLOPT_URL, ps->url);
1097     curl_easy_setopt(ps->send_endpoint, CURLOPT_PUT, 1L);
1098     curl_easy_setopt(ps->send_endpoint, CURLOPT_HEADERFUNCTION, &curl_put_header_function);
1099     curl_easy_setopt(ps->send_endpoint, CURLOPT_WRITEHEADER, ps);
1100     curl_easy_setopt(ps->send_endpoint, CURLOPT_READFUNCTION, send_curl_send_callback);
1101     curl_easy_setopt(ps->send_endpoint, CURLOPT_READDATA, ps);
1102     curl_easy_setopt(ps->send_endpoint, CURLOPT_WRITEFUNCTION, send_curl_receive_callback);
1103     curl_easy_setopt(ps->send_endpoint, CURLOPT_READDATA, ps);
1104     curl_easy_setopt(ps->send_endpoint, CURLOPT_TIMEOUT, (long) timeout.value);
1105     curl_easy_setopt(ps->send_endpoint, CURLOPT_PRIVATE, ps);
1106     curl_easy_setopt(ps->send_endpoint, CURLOPT_CONNECTTIMEOUT, HTTP_CONNECT_TIMEOUT);
1107     curl_easy_setopt(ps->send_endpoint, CURLOPT_BUFFERSIZE, GNUNET_SERVER_MAX_MESSAGE_SIZE);
1108
1109     mret = curl_multi_add_handle(plugin->multi_handle, ps->send_endpoint);
1110     if (mret != CURLM_OK)
1111     {
1112       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1113                   _("%s failed at %s:%d: `%s'\n"),
1114                   "curl_multi_add_handle", __FILE__, __LINE__,
1115                   curl_multi_strerror (mret));
1116       return -1;
1117     }
1118     bytes_sent = send_schedule (plugin, NULL);
1119     return bytes_sent;
1120   }
1121   if (ps->direction == INBOUND)
1122   {
1123     GNUNET_assert (NULL != ps->pending_msgs_tail);
1124     bytes_sent = 0;
1125     msg = ps->pending_msgs_tail;
1126     if ((ps->recv_connected==GNUNET_YES) && (ps->send_connected==GNUNET_YES))
1127         bytes_sent = msg->size;
1128     return bytes_sent;
1129   }
1130   return 0;
1131 }
1132
1133 static void send_execute (void *cls,
1134              const struct GNUNET_SCHEDULER_TaskContext *tc)
1135 {
1136   struct Plugin *plugin = cls;
1137   static unsigned int handles_last_run;
1138   int running;
1139   struct CURLMsg *msg;
1140   CURLMcode mret;
1141   struct Session *ps = NULL;
1142   struct HTTP_PeerContext *pc = NULL;
1143   struct HTTP_Message * cur_msg = NULL;
1144   long http_result;
1145
1146   GNUNET_assert(cls !=NULL);
1147   plugin->http_server_task_send = GNUNET_SCHEDULER_NO_TASK;
1148   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1149     return;
1150
1151   do
1152     {
1153       running = 0;
1154       mret = curl_multi_perform (plugin->multi_handle, &running);
1155       if (running < handles_last_run)
1156         {
1157           do
1158             {
1159
1160               msg = curl_multi_info_read (plugin->multi_handle, &running);
1161               if (msg == NULL)
1162                 break;
1163               /* get session for affected curl handle */
1164               GNUNET_assert ( msg->easy_handle != NULL );
1165               curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, (char *) &ps);
1166               GNUNET_assert ( ps != NULL );
1167               pc = ps->peercontext;
1168               GNUNET_assert ( pc != NULL );
1169               switch (msg->msg)
1170                 {
1171
1172                 case CURLMSG_DONE:
1173                   if ( (msg->data.result != CURLE_OK) &&
1174                        (msg->data.result != CURLE_GOT_NOTHING) )
1175                   {
1176                     /* sending msg failed*/
1177                     if (msg->easy_handle == ps->send_endpoint)
1178                     {
1179 #if DEBUG_CONNECTIONS
1180                       GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1181                                  _("Connection %X: HTTP PUT to peer `%s' (`%s') failed: `%s' `%s'\n"),
1182                                  ps,
1183                                  GNUNET_i2s(&pc->identity),
1184                                  http_plugin_address_to_string(NULL, ps->addr, ps->addrlen),
1185                                  "curl_multi_perform",
1186                                  curl_easy_strerror (msg->data.result));
1187 #endif
1188                       ps->send_connected = GNUNET_NO;
1189                       ps->send_active = GNUNET_NO;
1190                       curl_multi_remove_handle(plugin->multi_handle,msg->easy_handle);
1191                       curl_easy_cleanup(ps->send_endpoint);
1192                       ps->send_endpoint=NULL;
1193                       cur_msg = ps->pending_msgs_tail;
1194                       if (( NULL != cur_msg) && ( NULL != cur_msg->transmit_cont))
1195                         cur_msg->transmit_cont (cur_msg->transmit_cont_cls,&pc->identity,GNUNET_SYSERR);
1196                     }
1197                     /* GET connection failed */
1198                     if (msg->easy_handle == ps->recv_endpoint)
1199                     {
1200 #if DEBUG_CONNECTIONS
1201                       GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1202                            _("Connection %X: HTTP GET to peer `%s' (`%s') failed: `%s' `%s'\n"),
1203                            ps,
1204                            GNUNET_i2s(&pc->identity),
1205                            http_plugin_address_to_string(NULL, ps->addr, ps->addrlen),
1206                            "curl_multi_perform",
1207                            curl_easy_strerror (msg->data.result));
1208 #endif
1209                       ps->recv_connected = GNUNET_NO;
1210                       ps->recv_active = GNUNET_NO;
1211                       curl_multi_remove_handle(plugin->multi_handle,msg->easy_handle);
1212                       curl_easy_cleanup(ps->recv_endpoint);
1213                       ps->recv_endpoint=NULL;
1214                     }
1215                   }
1216                   else
1217                   {
1218                     if (msg->easy_handle == ps->send_endpoint)
1219                     {
1220                       GNUNET_assert (CURLE_OK == curl_easy_getinfo(msg->easy_handle, CURLINFO_RESPONSE_CODE, &http_result));
1221 #if DEBUG_CONNECTIONS
1222                       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1223                                   "Connection %X: HTTP PUT connection to peer `%s' (`%s') was closed with HTTP code %u\n",
1224                                    ps,
1225                                    GNUNET_i2s(&pc->identity),
1226                                    http_plugin_address_to_string(NULL, ps->addr, ps->addrlen),
1227                                    http_result);
1228 #endif
1229                       /* Calling transmit continuation  */
1230                       cur_msg = ps->pending_msgs_tail;
1231                       if (( NULL != cur_msg) && (NULL != cur_msg->transmit_cont))
1232                       {
1233                         /* HTTP 1xx : Last message before here was informational */
1234                         if ((http_result >=100) && (http_result < 200))
1235                           cur_msg->transmit_cont (cur_msg->transmit_cont_cls,&pc->identity,GNUNET_OK);
1236                         /* HTTP 2xx: successful operations */
1237                         if ((http_result >=200) && (http_result < 300))
1238                           cur_msg->transmit_cont (cur_msg->transmit_cont_cls,&pc->identity,GNUNET_OK);
1239                         /* HTTP 3xx..5xx: error */
1240                         if ((http_result >=300) && (http_result < 600))
1241                           cur_msg->transmit_cont (cur_msg->transmit_cont_cls,&pc->identity,GNUNET_SYSERR);
1242                       }
1243                       ps->send_connected = GNUNET_NO;
1244                       ps->send_active = GNUNET_NO;
1245                       curl_multi_remove_handle(plugin->multi_handle,msg->easy_handle);
1246                       curl_easy_cleanup(ps->send_endpoint);
1247                       ps->send_endpoint =NULL;
1248                     }
1249                     if (msg->easy_handle == ps->recv_endpoint)
1250                     {
1251 #if DEBUG_CONNECTIONS
1252                       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1253                                   "Connection %X: HTTP GET connection to peer `%s' (`%s') was closed with HTTP code %u\n",
1254                                    ps,
1255                                    GNUNET_i2s(&pc->identity),
1256                                    http_plugin_address_to_string(NULL, ps->addr, ps->addrlen),
1257                                    http_result);
1258 #endif
1259                       ps->recv_connected = GNUNET_NO;
1260                       ps->recv_active = GNUNET_NO;
1261                       curl_multi_remove_handle(plugin->multi_handle,msg->easy_handle);
1262                       curl_easy_cleanup(ps->recv_endpoint);
1263                       ps->recv_endpoint=NULL;
1264                     }
1265                   }
1266                   if (ps->pending_msgs_tail != NULL)
1267                   {
1268                     if (ps->pending_msgs_tail->pos>0)
1269                       remove_http_message(ps, ps->pending_msgs_tail);
1270                   }
1271                   return;
1272                 default:
1273                   break;
1274                 }
1275
1276             }
1277           while ( (running > 0) );
1278         }
1279       handles_last_run = running;
1280     }
1281   while (mret == CURLM_CALL_MULTI_PERFORM);
1282   send_schedule(plugin, cls);
1283 }
1284
1285
1286 /**
1287  * Function setting up file descriptors and scheduling task to run
1288  * @param ses session to send data to
1289  * @return bytes sent to peer
1290  */
1291 static size_t send_schedule(void *cls, struct Session* ses )
1292 {
1293   struct Plugin *plugin = cls;
1294   fd_set rs;
1295   fd_set ws;
1296   fd_set es;
1297   int max;
1298   struct GNUNET_NETWORK_FDSet *grs;
1299   struct GNUNET_NETWORK_FDSet *gws;
1300   long to;
1301   CURLMcode mret;
1302
1303   GNUNET_assert(cls !=NULL);
1304   max = -1;
1305   FD_ZERO (&rs);
1306   FD_ZERO (&ws);
1307   FD_ZERO (&es);
1308   mret = curl_multi_fdset (plugin->multi_handle, &rs, &ws, &es, &max);
1309   if (mret != CURLM_OK)
1310     {
1311       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1312                   _("%s failed at %s:%d: `%s'\n"),
1313                   "curl_multi_fdset", __FILE__, __LINE__,
1314                   curl_multi_strerror (mret));
1315       return -1;
1316     }
1317   mret = curl_multi_timeout (plugin->multi_handle, &to);
1318   if (mret != CURLM_OK)
1319     {
1320       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1321                   _("%s failed at %s:%d: `%s'\n"),
1322                   "curl_multi_timeout", __FILE__, __LINE__,
1323                   curl_multi_strerror (mret));
1324       return -1;
1325     }
1326
1327   grs = GNUNET_NETWORK_fdset_create ();
1328   gws = GNUNET_NETWORK_fdset_create ();
1329   GNUNET_NETWORK_fdset_copy_native (grs, &rs, max + 1);
1330   GNUNET_NETWORK_fdset_copy_native (gws, &ws, max + 1);
1331   plugin->http_server_task_send = GNUNET_SCHEDULER_add_select (plugin->env->sched,
1332                                    GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1333                                    GNUNET_SCHEDULER_NO_TASK,
1334                                    GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 0),
1335                                    grs,
1336                                    gws,
1337                                    &send_execute,
1338                                    plugin);
1339   GNUNET_NETWORK_fdset_destroy (gws);
1340   GNUNET_NETWORK_fdset_destroy (grs);
1341
1342   /* FIXME: return bytes REALLY sent */
1343   return 0;
1344 }
1345
1346
1347 /**
1348  * Function that can be used by the transport service to transmit
1349  * a message using the plugin.   Note that in the case of a
1350  * peer disconnecting, the continuation MUST be called
1351  * prior to the disconnect notification itself.  This function
1352  * will be called with this peer's HELLO message to initiate
1353  * a fresh connection to another peer.
1354  *
1355  * @param cls closure
1356  * @param target who should receive this message
1357  * @param msgbuf the message to transmit
1358  * @param msgbuf_size number of bytes in 'msgbuf'
1359  * @param priority how important is the message (most plugins will
1360  *                 ignore message priority and just FIFO)
1361  * @param timeout how long to wait at most for the transmission (does not
1362  *                require plugins to discard the message after the timeout,
1363  *                just advisory for the desired delay; most plugins will ignore
1364  *                this as well)
1365  * @param session which session must be used (or NULL for "any")
1366  * @param addr the address to use (can be NULL if the plugin
1367  *                is "on its own" (i.e. re-use existing TCP connection))
1368  * @param addrlen length of the address in bytes
1369  * @param force_address GNUNET_YES if the plugin MUST use the given address,
1370  *                GNUNET_NO means the plugin may use any other address and
1371  *                GNUNET_SYSERR means that only reliable existing
1372  *                bi-directional connections should be used (regardless
1373  *                of address)
1374  * @param cont continuation to call once the message has
1375  *        been transmitted (or if the transport is ready
1376  *        for the next transmission call; or if the
1377  *        peer disconnected...); can be NULL
1378  * @param cont_cls closure for cont
1379  * @return number of bytes used (on the physical network, with overheads);
1380  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
1381  *         and does NOT mean that the message was not transmitted (DV)
1382  */
1383 static ssize_t
1384 http_plugin_send (void *cls,
1385                   const struct GNUNET_PeerIdentity *target,
1386                   const char *msgbuf,
1387                   size_t msgbuf_size,
1388                   unsigned int priority,
1389                   struct GNUNET_TIME_Relative to,
1390                   struct Session *session,
1391                   const void *addr,
1392                   size_t addrlen,
1393                   int force_address,
1394                   GNUNET_TRANSPORT_TransmitContinuation cont,
1395                   void *cont_cls)
1396 {
1397   struct Plugin *plugin = cls;
1398   struct HTTP_Message *msg;
1399
1400   struct HTTP_PeerContext * pc;
1401   struct Session * ps;
1402
1403   GNUNET_assert(cls !=NULL);
1404   GNUNET_assert ((addr!=NULL) && (addrlen != 0));
1405
1406   pc = GNUNET_CONTAINER_multihashmap_get (plugin->peers, &target->hashPubKey);
1407   /* Peer unknown */
1408   if (pc==NULL)
1409   {
1410     pc = GNUNET_malloc(sizeof (struct HTTP_PeerContext));
1411     pc->plugin = plugin;
1412     memcpy(&pc->identity, target, sizeof(struct GNUNET_PeerIdentity));
1413     GNUNET_CONTAINER_multihashmap_put(plugin->peers, &pc->identity.hashPubKey, pc, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1414   }
1415   ps = get_Session(plugin, pc, addr, addrlen);
1416
1417   /* session not existing, but address forced -> creating new session */
1418   if ((force_address == GNUNET_YES) && (ps==NULL))
1419   {
1420     ps = GNUNET_malloc(sizeof (struct Session));
1421     ps->addr = GNUNET_malloc(addrlen);
1422     memcpy(ps->addr,addr,addrlen);
1423     ps->addrlen = addrlen;
1424     ps->direction=OUTBOUND;
1425     ps->recv_connected = GNUNET_NO;
1426     ps->send_connected = GNUNET_NO;
1427     ps->pending_msgs_head = NULL;
1428     ps->pending_msgs_tail = NULL;
1429     ps->peercontext=pc;
1430     ps->url = create_url (plugin, ps->addr, ps->addrlen);
1431     GNUNET_CONTAINER_DLL_insert(pc->head,pc->tail,ps);
1432   }
1433   /* session not existing, address not forced -> looking for other session */
1434   if ((ps==NULL) && (force_address == GNUNET_NO))
1435   {
1436     //struct PeerContext * tmp = pc->head;
1437
1438
1439     ps = GNUNET_malloc(sizeof (struct Session));
1440     ps->addr = GNUNET_malloc(addrlen);
1441     memcpy(ps->addr,addr,addrlen);
1442     ps->addrlen = addrlen;
1443     ps->direction=OUTBOUND;
1444     ps->recv_connected = GNUNET_NO;
1445     ps->send_connected = GNUNET_NO;
1446     ps->pending_msgs_head = NULL;
1447     ps->pending_msgs_tail = NULL;
1448     ps->peercontext=pc;
1449     ps->url = create_url (plugin, ps->addr, ps->addrlen);
1450     GNUNET_CONTAINER_DLL_insert(pc->head,pc->tail,ps);
1451   }
1452   if ((ps==NULL) && (force_address == GNUNET_SYSERR))
1453   {
1454     /* FIXME: CREATING SESSION, SHOULD CHOOSE EXISTING */
1455     ps = GNUNET_malloc(sizeof (struct Session));
1456     ps->addr = GNUNET_malloc(addrlen);
1457     memcpy(ps->addr,addr,addrlen);
1458     ps->addrlen = addrlen;
1459     ps->direction=OUTBOUND;
1460     ps->recv_connected = GNUNET_NO;
1461     ps->send_connected = GNUNET_NO;
1462     ps->pending_msgs_head = NULL;
1463     ps->pending_msgs_tail = NULL;
1464     ps->peercontext=pc;
1465     ps->url = create_url (plugin, ps->addr, ps->addrlen);
1466     GNUNET_CONTAINER_DLL_insert(pc->head,pc->tail,ps);
1467   }
1468
1469   char * force = GNUNET_malloc(30);
1470   if (force_address == GNUNET_YES)
1471     strcpy(force,"forced addr.");
1472   if (force_address == GNUNET_NO)
1473     strcpy(force,"any addr.");
1474   if (force_address == GNUNET_SYSERR)
1475     strcpy(force,"reliable bi-direc. address addr.");
1476   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Transport tells me to send %u bytes to `%s' %s (%s), session: %X\n",
1477                                       msgbuf_size,
1478                                       GNUNET_i2s(&pc->identity),
1479                                       force,
1480                                       http_plugin_address_to_string(NULL, addr, addrlen),
1481                                       ps);
1482
1483   GNUNET_free(force);
1484   /* create msg */
1485   msg = GNUNET_malloc (sizeof (struct HTTP_Message) + msgbuf_size);
1486   msg->next = NULL;
1487   msg->size = msgbuf_size;
1488   msg->pos = 0;
1489   msg->buf = (char *) &msg[1];
1490   msg->transmit_cont = cont;
1491   msg->transmit_cont_cls = cont_cls;
1492   memcpy (msg->buf,msgbuf, msgbuf_size);
1493   GNUNET_CONTAINER_DLL_insert(ps->pending_msgs_head,ps->pending_msgs_tail,msg);
1494
1495   return send_check_connections (plugin, session, ps);
1496 }
1497
1498
1499
1500 /**
1501  * Function that can be used to force the plugin to disconnect
1502  * from the given peer and cancel all previous transmissions
1503  * (and their continuationc).
1504  *
1505  * @param cls closure
1506  * @param target peer from which to disconnect
1507  */
1508 static void
1509 http_plugin_disconnect (void *cls,
1510                             const struct GNUNET_PeerIdentity *target)
1511 {
1512
1513   struct Plugin *plugin = cls;
1514   struct HTTP_PeerContext *pc = NULL;
1515   struct Session *ps = NULL;
1516
1517   pc = GNUNET_CONTAINER_multihashmap_get (plugin->peers, &target->hashPubKey);
1518   if (pc==NULL)
1519     return;
1520
1521   ps = pc->head;
1522
1523   while (ps!=NULL)
1524   {
1525     if (ps->direction==OUTBOUND)
1526     {
1527       if (ps->send_endpoint!=NULL)
1528       {
1529         curl_multi_remove_handle(plugin->multi_handle,ps->send_endpoint);
1530         curl_easy_cleanup(ps->send_endpoint);
1531         ps->send_endpoint=NULL;
1532       }
1533       if (ps->recv_endpoint!=NULL)
1534       {
1535        curl_multi_remove_handle(plugin->multi_handle,ps->recv_endpoint);
1536        curl_easy_cleanup(ps->recv_endpoint);
1537        ps->recv_endpoint=NULL;
1538       }
1539     }
1540     if (ps->direction==INBOUND)
1541     {
1542
1543     }
1544     while (ps->pending_msgs_head!=NULL)
1545     {
1546       remove_http_message(ps, ps->pending_msgs_head);
1547     }
1548     ps->recv_connected = GNUNET_NO;
1549     ps->recv_active = GNUNET_NO;
1550     ps->send_connected = GNUNET_NO;
1551     ps->send_active = GNUNET_NO;
1552     ps=ps->next;
1553   }
1554   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"All connections to peer `%s' terminated\n", GNUNET_i2s(target));
1555 }
1556
1557
1558 /**
1559  * Convert the transports address to a nice, human-readable
1560  * format.
1561  *
1562  * @param cls closure
1563  * @param type name of the transport that generated the address
1564  * @param addr one of the addresses of the host, NULL for the last address
1565  *        the specific address format depends on the transport
1566  * @param addrlen length of the address
1567  * @param numeric should (IP) addresses be displayed in numeric form?
1568  * @param timeout after how long should we give up?
1569  * @param asc function to call on each string
1570  * @param asc_cls closure for asc
1571  */
1572 static void
1573 http_plugin_address_pretty_printer (void *cls,
1574                                         const char *type,
1575                                         const void *addr,
1576                                         size_t addrlen,
1577                                         int numeric,
1578                                         struct GNUNET_TIME_Relative timeout,
1579                                         GNUNET_TRANSPORT_AddressStringCallback
1580                                         asc, void *asc_cls)
1581 {
1582   const struct IPv4HttpAddress *t4;
1583   const struct IPv6HttpAddress *t6;
1584   struct sockaddr_in a4;
1585   struct sockaddr_in6 a6;
1586   char * address;
1587   char * ret;
1588   unsigned int port;
1589   unsigned int res;
1590
1591   GNUNET_assert(cls !=NULL);
1592   if (addrlen == sizeof (struct IPv6HttpAddress))
1593   {
1594     address = GNUNET_malloc (INET6_ADDRSTRLEN);
1595     t6 = addr;
1596     a6.sin6_addr = t6->ipv6_addr;
1597     inet_ntop(AF_INET6, &(a6.sin6_addr),address,INET6_ADDRSTRLEN);
1598     port = ntohs(t6->u6_port);
1599   }
1600   else if (addrlen == sizeof (struct IPv4HttpAddress))
1601   {
1602     address = GNUNET_malloc (INET_ADDRSTRLEN);
1603     t4 = addr;
1604     a4.sin_addr.s_addr =  t4->ipv4_addr;
1605     inet_ntop(AF_INET, &(a4.sin_addr),address,INET_ADDRSTRLEN);
1606     port = ntohs(t4->u_port);
1607   }
1608   else
1609   {
1610     /* invalid address */
1611     GNUNET_break_op (0);
1612     asc (asc_cls, NULL);
1613     return;
1614   }
1615   res = GNUNET_asprintf(&ret,"http://%s:%u/",address,port);
1616   GNUNET_free (address);
1617   GNUNET_assert(res != 0);
1618
1619   asc (asc_cls, ret);
1620 }
1621
1622
1623
1624 /**
1625  * Another peer has suggested an address for this
1626  * peer and transport plugin.  Check that this could be a valid
1627  * address.  If so, consider adding it to the list
1628  * of addresses.
1629  *
1630  * @param cls closure
1631  * @param addr pointer to the address
1632  * @param addrlen length of addr
1633  * @return GNUNET_OK if this is a plausible address for this peer
1634  *         and transport
1635  */
1636 static int
1637 http_plugin_address_suggested (void *cls,
1638                                const void *addr, size_t addrlen)
1639 {
1640   struct Plugin *plugin = cls;
1641   struct IPv4HttpAddress *v4;
1642   struct IPv6HttpAddress *v6;
1643   unsigned int port;
1644
1645   GNUNET_assert(cls !=NULL);
1646   if ((addrlen != sizeof (struct IPv4HttpAddress)) &&
1647       (addrlen != sizeof (struct IPv6HttpAddress)))
1648     {
1649       return GNUNET_SYSERR;
1650     }
1651   if (addrlen == sizeof (struct IPv4HttpAddress))
1652     {
1653       v4 = (struct IPv4HttpAddress *) addr;
1654       if (INADDR_LOOPBACK == ntohl(v4->ipv4_addr))
1655       {
1656         return GNUNET_SYSERR;
1657       }
1658       port = ntohs (v4->u_port);
1659       if (port != plugin->port_inbound)
1660       {
1661         return GNUNET_SYSERR;
1662       }
1663     }
1664   else
1665     {
1666       v6 = (struct IPv6HttpAddress *) addr;
1667       if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1668         {
1669           return GNUNET_SYSERR;
1670         }
1671       port = ntohs (v6->u6_port);
1672       if (port != plugin->port_inbound)
1673       {
1674         return GNUNET_SYSERR;
1675       }
1676     }
1677   return GNUNET_OK;
1678 }
1679
1680
1681 /**
1682  * Function called for a quick conversion of the binary address to
1683  * a numeric address.  Note that the caller must not free the
1684  * address and that the next call to this function is allowed
1685  * to override the address again.
1686  *
1687  * @param cls closure
1688  * @param addr binary address
1689  * @param addrlen length of the address
1690  * @return string representing the same address
1691  */
1692 static const char*
1693 http_plugin_address_to_string (void *cls,
1694                                    const void *addr,
1695                                    size_t addrlen)
1696 {
1697   const struct IPv4HttpAddress *t4;
1698   const struct IPv6HttpAddress *t6;
1699   struct sockaddr_in a4;
1700   struct sockaddr_in6 a6;
1701   char * address;
1702   char * ret;
1703   uint16_t port;
1704   unsigned int res;
1705
1706   if (addrlen == sizeof (struct IPv6HttpAddress))
1707     {
1708       address = GNUNET_malloc (INET6_ADDRSTRLEN);
1709       t6 = addr;
1710       a6.sin6_addr = t6->ipv6_addr;
1711       inet_ntop(AF_INET6, &(a6.sin6_addr),address,INET6_ADDRSTRLEN);
1712       port = ntohs(t6->u6_port);
1713     }
1714   else if (addrlen == sizeof (struct IPv4HttpAddress))
1715     {
1716       address = GNUNET_malloc (INET_ADDRSTRLEN);
1717       t4 = addr;
1718       a4.sin_addr.s_addr =  t4->ipv4_addr;
1719       inet_ntop(AF_INET, &(a4.sin_addr),address,INET_ADDRSTRLEN);
1720       port = ntohs(t4->u_port);
1721     }
1722   else
1723     {
1724       /* invalid address */
1725       return NULL;
1726     }
1727   res = GNUNET_asprintf(&ret,"%s:%u",address,port);
1728   GNUNET_free (address);
1729   GNUNET_assert(res != 0);
1730   return ret;
1731 }
1732
1733 /**
1734  * Add the IP of our network interface to the list of
1735  * our external IP addresses.
1736  *
1737  * @param cls the 'struct Plugin*'
1738  * @param name name of the interface
1739  * @param isDefault do we think this may be our default interface
1740  * @param addr address of the interface
1741  * @param addrlen number of bytes in addr
1742  * @return GNUNET_OK to continue iterating
1743  */
1744 static int
1745 process_interfaces (void *cls,
1746                     const char *name,
1747                     int isDefault,
1748                     const struct sockaddr *addr, socklen_t addrlen)
1749 {
1750   struct Plugin *plugin = cls;
1751   struct IPv4HttpAddress * t4;
1752   struct IPv6HttpAddress * t6;
1753   int af;
1754
1755   GNUNET_assert(cls !=NULL);
1756   af = addr->sa_family;
1757   if (af == AF_INET)
1758     {
1759       t4 = GNUNET_malloc(sizeof(struct IPv4HttpAddress));
1760       if (INADDR_LOOPBACK == ntohl(((struct sockaddr_in *) addr)->sin_addr.s_addr))
1761       {
1762         /* skip loopback addresses */
1763         return GNUNET_OK;
1764       }
1765       t4->ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1766       t4->u_port = htons (plugin->port_inbound);
1767       plugin->env->notify_address(plugin->env->cls,"http",t4, sizeof (struct IPv4HttpAddress), GNUNET_TIME_UNIT_FOREVER_REL);
1768
1769     }
1770   else if (af == AF_INET6)
1771     {
1772       t6 = GNUNET_malloc(sizeof(struct IPv6HttpAddress));
1773       if (IN6_IS_ADDR_LINKLOCAL (&((struct sockaddr_in6 *) addr)->sin6_addr))
1774         {
1775           /* skip link local addresses */
1776           return GNUNET_OK;
1777         }
1778       if (IN6_IS_ADDR_LOOPBACK (&((struct sockaddr_in6 *) addr)->sin6_addr))
1779         {
1780           /* skip loopback addresses */
1781           return GNUNET_OK;
1782         }
1783       memcpy (&t6->ipv6_addr,
1784               &((struct sockaddr_in6 *) addr)->sin6_addr,
1785               sizeof (struct in6_addr));
1786       t6->u6_port = htons (plugin->port_inbound);
1787       plugin->env->notify_address(plugin->env->cls,"http",t6,sizeof (struct IPv6HttpAddress) , GNUNET_TIME_UNIT_FOREVER_REL);
1788     }
1789   return GNUNET_OK;
1790 }
1791
1792 int peer_context_Iterator (void *cls, const GNUNET_HashCode *key, void *value)
1793 {
1794   struct HTTP_PeerContext * pc = value;
1795   struct Session * ps = pc->head;
1796   struct Session * tmp = NULL;
1797   struct HTTP_Message * msg = NULL;
1798   struct HTTP_Message * msg_tmp = NULL;
1799
1800   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Freeing context for peer `%s'\n",GNUNET_i2s(&pc->identity));
1801
1802   while (ps!=NULL)
1803   {
1804     tmp = ps->next;
1805
1806     GNUNET_free(ps->addr);
1807     GNUNET_free(ps->url);
1808     if (ps->msgtok != NULL)
1809       GNUNET_SERVER_mst_destroy (ps->msgtok);
1810
1811     msg = ps->pending_msgs_head;
1812     while (msg!=NULL)
1813     {
1814       msg_tmp = msg->next;
1815       GNUNET_free(msg);
1816       msg = msg_tmp;
1817     }
1818     if (ps->direction==OUTBOUND)
1819     {
1820       if (ps->send_endpoint!=NULL)
1821         curl_easy_cleanup(ps->send_endpoint);
1822       if (ps->recv_endpoint!=NULL)
1823         curl_easy_cleanup(ps->recv_endpoint);
1824     }
1825
1826     GNUNET_free(ps);
1827     ps=tmp;
1828   }
1829   GNUNET_free(pc);
1830   return GNUNET_YES;
1831 }
1832
1833
1834 /**
1835  * Exit point from the plugin.
1836  */
1837 void *
1838 libgnunet_plugin_transport_http_done (void *cls)
1839 {
1840   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1841   struct Plugin *plugin = api->cls;
1842   CURLMcode mret;
1843
1844   GNUNET_assert(cls !=NULL);
1845
1846   if ( plugin->http_server_task_v4 != GNUNET_SCHEDULER_NO_TASK)
1847   {
1848     GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_server_task_v4);
1849     plugin->http_server_task_v4 = GNUNET_SCHEDULER_NO_TASK;
1850   }
1851
1852   if ( plugin->http_server_task_v6 != GNUNET_SCHEDULER_NO_TASK)
1853   {
1854     GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_server_task_v6);
1855     plugin->http_server_task_v6 = GNUNET_SCHEDULER_NO_TASK;
1856   }
1857
1858   if ( plugin->http_server_task_send != GNUNET_SCHEDULER_NO_TASK)
1859   {
1860     GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_server_task_send);
1861     plugin->http_server_task_send = GNUNET_SCHEDULER_NO_TASK;
1862   }
1863
1864   if (plugin->http_server_daemon_v4 != NULL)
1865   {
1866     MHD_stop_daemon (plugin->http_server_daemon_v4);
1867     plugin->http_server_daemon_v4 = NULL;
1868   }
1869   if (plugin->http_server_daemon_v6 != NULL)
1870   {
1871     MHD_stop_daemon (plugin->http_server_daemon_v6);
1872     plugin->http_server_daemon_v6 = NULL;
1873   }
1874
1875   /* free all peer information */
1876   GNUNET_CONTAINER_multihashmap_iterate (plugin->peers,
1877                                          &peer_context_Iterator,
1878                                          NULL);
1879   GNUNET_CONTAINER_multihashmap_destroy (plugin->peers);
1880
1881   mret = curl_multi_cleanup(plugin->multi_handle);
1882   if ( CURLM_OK != mret)
1883     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"curl multihandle clean up failed");
1884
1885   GNUNET_free (plugin);
1886   GNUNET_free (api);
1887   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Unload http plugin complete...\n");
1888   return NULL;
1889 }
1890
1891
1892 /**
1893  * Entry point for the plugin.
1894  */
1895 void *
1896 libgnunet_plugin_transport_http_init (void *cls)
1897 {
1898   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1899   struct Plugin *plugin;
1900   struct GNUNET_TRANSPORT_PluginFunctions *api;
1901   struct GNUNET_TIME_Relative gn_timeout;
1902   long long unsigned int port;
1903
1904   GNUNET_assert(cls !=NULL);
1905   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting http plugin...\n");
1906
1907   plugin = GNUNET_malloc (sizeof (struct Plugin));
1908   plugin->env = env;
1909   plugin->peers = NULL;
1910
1911   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1912   api->cls = plugin;
1913   api->send = &http_plugin_send;
1914   api->disconnect = &http_plugin_disconnect;
1915   api->address_pretty_printer = &http_plugin_address_pretty_printer;
1916   api->check_address = &http_plugin_address_suggested;
1917   api->address_to_string = &http_plugin_address_to_string;
1918
1919   /* Hashing our identity to use it in URLs */
1920   GNUNET_CRYPTO_hash_to_enc ( &(plugin->env->my_identity->hashPubKey), &plugin->my_ascii_hash_ident);
1921
1922   /* Reading port number from config file */
1923   if ((GNUNET_OK !=
1924        GNUNET_CONFIGURATION_get_value_number (env->cfg,
1925                                               "transport-http",
1926                                               "PORT",
1927                                               &port)) ||
1928       (port > 65535) )
1929     {
1930       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1931                        "http",
1932                        _
1933                        ("Require valid port number for transport plugin `%s' in configuration!\n"),
1934                        "transport-http");
1935       libgnunet_plugin_transport_http_done (api);
1936       return NULL;
1937     }
1938   GNUNET_assert ((port > 0) && (port <= 65535));
1939   plugin->port_inbound = port;
1940   gn_timeout = GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT;
1941   if ((plugin->http_server_daemon_v4 == NULL) && (plugin->http_server_daemon_v6 == NULL) && (port != 0))
1942     {
1943     plugin->http_server_daemon_v6 = MHD_start_daemon (MHD_USE_IPv6,
1944                                        port,
1945                                        &acceptPolicyCallback,
1946                                        plugin , &accessHandlerCallback, plugin,
1947                                        MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
1948                                        MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
1949                                        MHD_OPTION_CONNECTION_TIMEOUT, (gn_timeout.value / 1000),
1950                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
1951                                        MHD_OPTION_NOTIFY_COMPLETED, &requestCompletedCallback, NULL,
1952                                        MHD_OPTION_END);
1953     plugin->http_server_daemon_v4 = MHD_start_daemon (MHD_NO_FLAG,
1954                                        port,
1955                                        &acceptPolicyCallback,
1956                                        plugin , &accessHandlerCallback, plugin,
1957                                        MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
1958                                        MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
1959                                        MHD_OPTION_CONNECTION_TIMEOUT, (gn_timeout.value / 1000),
1960                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
1961                                        MHD_OPTION_NOTIFY_COMPLETED, &requestCompletedCallback, NULL,
1962                                        MHD_OPTION_END);
1963     }
1964   if (plugin->http_server_daemon_v4 != NULL)
1965     plugin->http_server_task_v4 = http_server_daemon_prepare (plugin, plugin->http_server_daemon_v4);
1966   if (plugin->http_server_daemon_v6 != NULL)
1967     plugin->http_server_task_v6 = http_server_daemon_prepare (plugin, plugin->http_server_daemon_v6);
1968
1969   if (plugin->http_server_task_v4 != GNUNET_SCHEDULER_NO_TASK)
1970     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD with IPv4 on port %u\n",port);
1971   else if (plugin->http_server_task_v6 != GNUNET_SCHEDULER_NO_TASK)
1972     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD with IPv4 and IPv6 on port %u\n",port);
1973   else
1974   {
1975     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"No MHD was started, transport plugin not functional!\n");
1976     libgnunet_plugin_transport_http_done (api);
1977     return NULL;
1978   }
1979
1980   /* Initializing cURL */
1981   curl_global_init(CURL_GLOBAL_ALL);
1982   plugin->multi_handle = curl_multi_init();
1983
1984   if ( NULL == plugin->multi_handle )
1985   {
1986     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1987                      "http",
1988                      _("Could not initialize curl multi handle, failed to start http plugin!\n"),
1989                      "transport-http");
1990     libgnunet_plugin_transport_http_done (api);
1991     return NULL;
1992   }
1993
1994   plugin->peers = GNUNET_CONTAINER_multihashmap_create (10);
1995   GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
1996
1997   return api;
1998 }
1999
2000 /* end of plugin_transport_http.c */