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