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