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