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