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