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