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