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