changes
[oweals/gnunet.git] / src / transport / plugin_transport_http_client.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 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file transport/plugin_transport_http_client.c
23  * @brief HTTP/S client transport plugin
24  * @author Matthias Wachs
25  */
26
27 #if BUILD_HTTPS
28 #define LIBGNUNET_PLUGIN_TRANSPORT_INIT libgnunet_plugin_transport_https_client_init
29 #define LIBGNUNET_PLUGIN_TRANSPORT_DONE libgnunet_plugin_transport_https_client_done
30 #else
31 #define LIBGNUNET_PLUGIN_TRANSPORT_INIT libgnunet_plugin_transport_http_client_init
32 #define LIBGNUNET_PLUGIN_TRANSPORT_DONE libgnunet_plugin_transport_http_client_done
33 #endif
34
35
36 #define HTTP_NOT_VALIDATED_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
37
38 #include "platform.h"
39 #include "gnunet_protocols.h"
40 #include "gnunet_connection_lib.h"
41 #include "gnunet_server_lib.h"
42 #include "gnunet_service_lib.h"
43 #include "gnunet_statistics_service.h"
44 #include "gnunet_transport_service.h"
45 #include "gnunet_transport_plugin.h"
46 #include "plugin_transport_http_common.h"
47 #include <curl/curl.h>
48
49
50 /**
51  * Encapsulation of all of the state of the plugin.
52  */
53 struct HTTP_Client_Plugin;
54
55
56 /**
57  *  Message to send using http
58  */
59 struct HTTP_Message
60 {
61   /**
62    * next pointer for double linked list
63    */
64   struct HTTP_Message *next;
65
66   /**
67    * previous pointer for double linked list
68    */
69   struct HTTP_Message *prev;
70
71   /**
72    * buffer containing data to send
73    */
74   char *buf;
75
76   /**
77    * amount of data already sent
78    */
79   size_t pos;
80
81   /**
82    * buffer length
83    */
84   size_t size;
85
86   /**
87    * Continuation function to call once the transmission buffer
88    * has again space available.  NULL if there is no
89    * continuation to call.
90    */
91   GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
92
93   /**
94    * Closure for transmit_cont.
95    */
96   void *transmit_cont_cls;
97 };
98
99
100 /**
101  * Session handle for connections.
102  */
103 struct Session
104 {
105   /**
106    * To whom are we talking to (set to our identity
107    * if we are still waiting for the welcome message)
108    */
109   struct GNUNET_PeerIdentity target;
110
111   /**
112    * Stored in a linked list.
113    */
114   struct Session *next;
115
116   /**
117    * Stored in a linked list.
118    */
119   struct Session *prev;
120
121   /**
122    * Address
123    */
124   void *addr;
125
126   /**
127    * Address length
128    */
129   size_t addrlen;
130
131   /**
132    * ATS network type in NBO
133    */
134   uint32_t ats_address_network_type;
135
136   /**
137    * Pointer to the global plugin struct.
138    */
139   struct HTTP_Client_Plugin *plugin;
140
141   /**
142    * Is client send handle paused since there are no data to send?
143    * GNUNET_YES/NO
144    */
145   int client_put_paused;
146
147
148   /**
149    * Client send handle
150    */
151   void *client_put;
152
153   /**
154    * Client receive handle
155    */
156   void *client_get;
157
158   /**
159    * next pointer for double linked list
160    */
161   struct HTTP_Message *msg_head;
162
163   /**
164    * previous pointer for double linked list
165    */
166   struct HTTP_Message *msg_tail;
167
168   /**
169    * Message stream tokenizer for incoming data
170    */
171   struct GNUNET_SERVER_MessageStreamTokenizer *msg_tk;
172
173   /**
174    * Session timeout task
175    */
176   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
177
178   /**
179    * Task to wake up client receive handle when receiving is allowed again
180    */
181   GNUNET_SCHEDULER_TaskIdentifier recv_wakeup_task;
182
183   /**
184   * Absolute time when to receive data again
185   * Used for receive throttling
186   */
187  struct GNUNET_TIME_Absolute next_receive;
188 };
189
190 /**
191  * Encapsulation of all of the state of the plugin.
192  */
193 struct HTTP_Client_Plugin
194 {
195   /**
196    * Our environment.
197    */
198   struct GNUNET_TRANSPORT_PluginEnvironment *env;
199
200   /**
201    * Linked list head of open sessions.
202    */
203   struct Session *head;
204
205   /**
206    * Linked list tail of open sessions.
207    */
208   struct Session *tail;
209
210   /**
211    * Plugin name
212    */
213   char *name;
214
215   /**
216    * Protocol
217    */
218   char *protocol;
219
220   /**
221    * Maximum number of sockets the plugin can use
222    * Each http inbound /outbound connections are two connections
223    */
224   unsigned int max_connections;
225
226   /**
227    * Current number of sockets the plugin can use
228    * Each http inbound /outbound connections are two connections
229    */
230   unsigned int cur_connections;
231
232   /**
233    * Last used unique HTTP connection tag
234    */
235   uint32_t last_tag;
236
237   /**
238    * use IPv6
239    */
240   uint16_t use_ipv6;
241
242   /**
243    * use IPv4
244    */
245   uint16_t use_ipv4;
246
247   /**
248    * cURL Multihandle
249    */
250   CURLM *curl_multi_handle;
251
252   /**
253    * curl perform task
254    */
255   GNUNET_SCHEDULER_TaskIdentifier client_perform_task;
256 };
257
258 /**
259  * Encapsulation of all of the state of the plugin.
260  */
261 struct HTTP_Client_Plugin *p;
262
263 /**
264  * Start session timeout
265  */
266 static void
267 client_start_session_timeout (struct Session *s);
268
269 /**
270  * Increment session timeout due to activity
271  */
272 static void
273 client_reschedule_session_timeout (struct Session *s);
274
275 /**
276  * Cancel timeout
277  */
278 static void
279 client_stop_session_timeout (struct Session *s);
280
281
282 /**
283  * Function that can be used by the transport service to transmit
284  * a message using the plugin.   Note that in the case of a
285  * peer disconnecting, the continuation MUST be called
286  * prior to the disconnect notification itself.  This function
287  * will be called with this peer's HELLO message to initiate
288  * a fresh connection to another peer.
289  *
290  * @param cls closure
291  * @param session which session must be used
292  * @param msgbuf the message to transmit
293  * @param msgbuf_size number of bytes in 'msgbuf'
294  * @param priority how important is the message (most plugins will
295  *                 ignore message priority and just FIFO)
296  * @param to how long to wait at most for the transmission (does not
297  *                require plugins to discard the message after the timeout,
298  *                just advisory for the desired delay; most plugins will ignore
299  *                this as well)
300  * @param cont continuation to call once the message has
301  *        been transmitted (or if the transport is ready
302  *        for the next transmission call; or if the
303  *        peer disconnected...); can be NULL
304  * @param cont_cls closure for cont
305  * @return number of bytes used (on the physical network, with overheads);
306  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
307  *         and does NOT mean that the message was not transmitted (DV)
308  */
309 static ssize_t
310 http_client_plugin_send (void *cls,
311                   struct Session *session,
312                   const char *msgbuf, size_t msgbuf_size,
313                   unsigned int priority,
314                   struct GNUNET_TIME_Relative to,
315                   GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
316 {
317   struct HTTP_Client_Plugin *plugin = cls;
318   int bytes_sent = 0;
319
320   GNUNET_assert (plugin != NULL);
321   GNUNET_assert (session != NULL);
322
323   GNUNET_break (0);
324
325   /*  struct Plugin *plugin = cls; */
326   return bytes_sent;
327 }
328
329
330
331 /**
332  * Function that can be used to force the plugin to disconnect
333  * from the given peer and cancel all previous transmissions
334  * (and their continuationc).
335  *
336  * @param cls closure
337  * @param target peer from which to disconnect
338  */
339 static void
340 http_client_plugin_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
341 {
342   // struct Plugin *plugin = cls;
343   // FIXME
344   GNUNET_break (0);
345 }
346
347 static struct Session *
348 client_lookup_session (struct HTTP_Client_Plugin *plugin,
349                        const struct GNUNET_HELLO_Address *address)
350 {
351   struct Session *pos;
352
353   for (pos = plugin->head; NULL != pos; pos = pos->next)
354     if ((0 == memcmp (&address->peer, &pos->target, sizeof (struct GNUNET_PeerIdentity))) &&
355         (address->address_length == pos->addrlen) &&
356         (0 == memcmp (address->address, pos->addr, pos->addrlen)))
357       return pos;
358   return NULL;
359 }
360
361 static int
362 client_exist_session (struct HTTP_Client_Plugin *plugin, struct Session *s)
363 {
364   struct Session * head;
365
366   GNUNET_assert (NULL != plugin);
367   GNUNET_assert (NULL != s);
368
369   for (head = plugin->head; head != NULL; head = head->next)
370   {
371     if (head == s)
372       return GNUNET_YES;
373   }
374   return GNUNET_NO;
375 }
376
377 /**
378  * Callback method used with libcurl
379  * Method is called when libcurl needs to read data during sending
380  *
381  * @param stream pointer where to write data
382  * @param size size of an individual element
383  * @param nmemb count of elements that can be written to the buffer
384  * @param cls source pointer, passed to the libcurl handle
385  * @return bytes written to stream, returning 0 will terminate connection!
386  */
387 static size_t
388 client_send_cb (void *stream, size_t size, size_t nmemb, void *cls)
389 {
390   struct Session *s = cls;
391   struct HTTP_Client_Plugin *plugin = s->plugin;
392   struct HTTP_Message *msg = s->msg_head;
393   size_t len;
394
395   if (GNUNET_YES != client_exist_session (plugin, s))
396   {
397     GNUNET_break (0);
398     return 0;
399   }
400   if (NULL == msg)
401   {
402     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
403                      "Nothing to for session %p send! Suspending PUT handle!\n", s);
404     s->client_put_paused = GNUNET_YES;
405     return CURL_READFUNC_PAUSE;
406   }
407   /* data to send */
408   GNUNET_assert (msg->pos < msg->size);
409   /* calculate how much fits in buffer */
410   len = GNUNET_MIN (msg->size - msg->pos,
411                     size * nmemb);
412   memcpy (stream, &msg->buf[msg->pos], len);
413   msg->pos += len;
414   if (msg->pos == msg->size)
415   {
416     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
417                      "Session %p message with %u bytes sent, removing message from queue\n",
418                      s, msg->size, msg->pos);
419     /* Calling transmit continuation  */
420     GNUNET_CONTAINER_DLL_remove (s->msg_head, s->msg_tail, msg);
421     if (NULL != msg->transmit_cont)
422       msg->transmit_cont (msg->transmit_cont_cls, &s->target, GNUNET_OK);
423     GNUNET_free (msg);
424   }
425   client_reschedule_session_timeout (s);
426   return len;
427 }
428
429
430 static void
431 client_wake_up (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
432 {
433   struct Session *s = cls;
434
435   if (GNUNET_YES != client_exist_session(p, s))
436   {
437     GNUNET_break (0);
438     return;
439   }
440   s->recv_wakeup_task = GNUNET_SCHEDULER_NO_TASK;
441   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
442     return;
443   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, s->plugin->name,
444                    "Client: %p Waking up receive handle\n", s->client_get);
445   if (s->client_get != NULL)
446     curl_easy_pause (s->client_get, CURLPAUSE_CONT);
447 }
448
449
450
451 static int
452 client_receive_mst_cb (void *cls, void *client,
453                        const struct GNUNET_MessageHeader *message)
454 {
455   struct Session *s = cls;
456   struct HTTP_Client_Plugin *plugin;
457   struct GNUNET_TIME_Relative delay;
458   struct GNUNET_ATS_Information atsi[2];
459
460   if (GNUNET_YES != client_exist_session(p, s))
461   {
462     GNUNET_break (0);
463     return GNUNET_OK;
464   }
465   plugin = s->plugin;
466
467
468   atsi[0].type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
469   atsi[0].value = htonl (1);
470   atsi[1].type = htonl (GNUNET_ATS_NETWORK_TYPE);
471   atsi[1].value = s->ats_address_network_type;
472   GNUNET_break (s->ats_address_network_type != ntohl (GNUNET_ATS_NET_UNSPECIFIED));
473
474   delay = s->plugin->env->receive (plugin->env->cls, &s->target, message,
475                                    (const struct GNUNET_ATS_Information *) &atsi, 2,
476                                    s, s->addr, s->addrlen);
477   s->next_receive =
478       GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (), delay);
479
480   if (GNUNET_TIME_absolute_get ().abs_value < s->next_receive.abs_value)
481   {
482
483     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
484                      "Client: peer `%s' address `%s' next read delayed for %llu ms\n",
485                      GNUNET_i2s (&s->target), GNUNET_a2s (s->addr, s->addrlen),
486                      delay);
487   }
488   client_reschedule_session_timeout (s);
489   return GNUNET_OK;
490 }
491
492
493
494 /**
495  * Callback method used with libcurl
496  * Method is called when libcurl needs to write data during sending
497  *
498  * @param stream pointer where to write data
499  * @param size size of an individual element
500  * @param nmemb count of elements that can be written to the buffer
501  * @param cls destination pointer, passed to the libcurl handle
502  * @return bytes read from stream
503  */
504 static size_t
505 client_receive (void *stream, size_t size, size_t nmemb, void *cls)
506 {
507   return 0;
508
509   struct Session *s = cls;
510   struct GNUNET_TIME_Absolute now;
511   size_t len = size * nmemb;
512   struct HTTP_Client_Plugin *plugin = s->plugin;
513
514   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
515                    "Received %u bytes from peer `%s'\n", len,
516                    GNUNET_i2s (&s->target));
517   now = GNUNET_TIME_absolute_get ();
518   if (now.abs_value < s->next_receive.abs_value)
519   {
520     struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
521     struct GNUNET_TIME_Relative delta =
522         GNUNET_TIME_absolute_get_difference (now, s->next_receive);
523     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
524                      "No inbound bandwidth for session %p available! Next read was delayed for %llu ms\n",
525                      s, delta.rel_value);
526     if (s->recv_wakeup_task != GNUNET_SCHEDULER_NO_TASK)
527     {
528       GNUNET_SCHEDULER_cancel (s->recv_wakeup_task);
529       s->recv_wakeup_task = GNUNET_SCHEDULER_NO_TASK;
530     }
531     s->recv_wakeup_task =
532         GNUNET_SCHEDULER_add_delayed (delta, &client_wake_up, s);
533     return CURLPAUSE_ALL;
534   }
535   if (NULL == s->msg_tk)
536     s->msg_tk = GNUNET_SERVER_mst_create (&client_receive_mst_cb, s);
537   GNUNET_SERVER_mst_receive (s->msg_tk, s, stream, len, GNUNET_NO, GNUNET_NO);
538   return len;
539
540 }
541
542 /**
543  * Task performing curl operations
544  *
545  * @param cls plugin as closure
546  * @param tc gnunet scheduler task context
547  */
548 static void
549 client_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
550
551 /**
552  * Function setting up file descriptors and scheduling task to run
553  *
554  * @param  plugin plugin as closure
555  * @param now schedule task in 1ms, regardless of what curl may say
556  * @return GNUNET_SYSERR for hard failure, GNUNET_OK for ok
557  */
558 static int
559 client_schedule (struct HTTP_Client_Plugin *plugin, int now)
560 {
561   fd_set rs;
562   fd_set ws;
563   fd_set es;
564   int max;
565   struct GNUNET_NETWORK_FDSet *grs;
566   struct GNUNET_NETWORK_FDSet *gws;
567   long to;
568   CURLMcode mret;
569   struct GNUNET_TIME_Relative timeout;
570
571   /* Cancel previous scheduled task */
572   if (plugin->client_perform_task != GNUNET_SCHEDULER_NO_TASK)
573   {
574     GNUNET_SCHEDULER_cancel (plugin->client_perform_task);
575     plugin->client_perform_task = GNUNET_SCHEDULER_NO_TASK;
576   }
577   max = -1;
578   FD_ZERO (&rs);
579   FD_ZERO (&ws);
580   FD_ZERO (&es);
581   mret = curl_multi_fdset (plugin->curl_multi_handle, &rs, &ws, &es, &max);
582   if (mret != CURLM_OK)
583   {
584     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("%s failed at %s:%d: `%s'\n"),
585                 "curl_multi_fdset", __FILE__, __LINE__,
586                 curl_multi_strerror (mret));
587     return GNUNET_SYSERR;
588   }
589   mret = curl_multi_timeout (plugin->curl_multi_handle, &to);
590   if (to == -1)
591     timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1);
592   else
593     timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, to);
594   if (now == GNUNET_YES)
595     timeout = GNUNET_TIME_UNIT_MILLISECONDS;
596
597   if (mret != CURLM_OK)
598   {
599     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("%s failed at %s:%d: `%s'\n"),
600                 "curl_multi_timeout", __FILE__, __LINE__,
601                 curl_multi_strerror (mret));
602     return GNUNET_SYSERR;
603   }
604
605   grs = GNUNET_NETWORK_fdset_create ();
606   gws = GNUNET_NETWORK_fdset_create ();
607   GNUNET_NETWORK_fdset_copy_native (grs, &rs, max + 1);
608   GNUNET_NETWORK_fdset_copy_native (gws, &ws, max + 1);
609
610   plugin->client_perform_task =
611       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
612                                    timeout, grs, gws,
613                                    &client_run, plugin);
614   GNUNET_NETWORK_fdset_destroy (gws);
615   GNUNET_NETWORK_fdset_destroy (grs);
616   return GNUNET_OK;
617 }
618
619
620
621 static int
622 client_disconnect (struct Session *s)
623 {
624
625   int res = GNUNET_OK;
626   CURLMcode mret;
627   struct HTTP_Client_Plugin *plugin = s->plugin;
628   struct HTTP_Message *msg;
629   struct HTTP_Message *t;
630
631   if (GNUNET_YES != client_exist_session (plugin, s))
632   {
633     GNUNET_break (0);
634     return GNUNET_SYSERR;
635   }
636
637   if (s->client_put != NULL)
638   {
639     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
640                      "Client: %p / %p Deleting outbound PUT session to peer `%s'\n",
641                      s, s->client_put, GNUNET_i2s (&s->target));
642
643     /* remove curl handle from multi handle */
644     mret = curl_multi_remove_handle (plugin->curl_multi_handle, s->client_put);
645     if (mret != CURLM_OK)
646     {
647       /* clean up easy handle, handle is now invalid and free'd */
648       res = GNUNET_SYSERR;
649       GNUNET_break (0);
650     }
651     curl_easy_cleanup (s->client_put);
652     s->client_put = NULL;
653   }
654
655
656   if (s->recv_wakeup_task != GNUNET_SCHEDULER_NO_TASK)
657   {
658     GNUNET_SCHEDULER_cancel (s->recv_wakeup_task);
659     s->recv_wakeup_task = GNUNET_SCHEDULER_NO_TASK;
660   }
661
662   if (s->client_get != NULL)
663   {
664     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
665                      "Client: %p / %p Deleting outbound GET session to peer `%s'\n",
666                      s,
667                      s->client_get, GNUNET_i2s (&s->target));
668
669     /* remove curl handle from multi handle */
670     mret = curl_multi_remove_handle (plugin->curl_multi_handle, s->client_get);
671     if (mret != CURLM_OK)
672     {
673       /* clean up easy handle, handle is now invalid and free'd */
674       res = GNUNET_SYSERR;
675       GNUNET_break (0);
676     }
677     curl_easy_cleanup (s->client_get);
678     s->client_get = NULL;
679   }
680
681   msg = s->msg_head;
682   while (msg != NULL)
683   {
684     t = msg->next;
685     if (NULL != msg->transmit_cont)
686       msg->transmit_cont (msg->transmit_cont_cls, &s->target, GNUNET_SYSERR);
687     GNUNET_CONTAINER_DLL_remove (s->msg_head, s->msg_tail, msg);
688     GNUNET_free (msg);
689     msg = t;
690   }
691
692   plugin->cur_connections -= 2;
693   plugin->env->session_end (plugin->env->cls, &s->target, s);
694
695   GNUNET_assert (plugin->cur_connections > 0);
696   plugin->cur_connections --;
697   GNUNET_STATISTICS_set (plugin->env->stats,
698       "# HTTP client connections",
699       plugin->cur_connections,
700       GNUNET_NO);
701
702   /* Re-schedule since handles have changed */
703   if (plugin->client_perform_task != GNUNET_SCHEDULER_NO_TASK)
704   {
705     GNUNET_SCHEDULER_cancel (plugin->client_perform_task);
706     plugin->client_perform_task = GNUNET_SCHEDULER_NO_TASK;
707   }
708   client_schedule (plugin, GNUNET_YES);
709
710   return res;
711 }
712
713
714 /**
715  * Task performing curl operations
716  *
717  * @param cls plugin as closure
718  * @param tc gnunet scheduler task context
719  */
720 static void
721 client_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
722 {
723   GNUNET_break (0);
724   struct HTTP_Client_Plugin *plugin = cls;
725   int running;
726   CURLMcode mret;
727
728   GNUNET_assert (cls != NULL);
729
730   plugin->client_perform_task = GNUNET_SCHEDULER_NO_TASK;
731   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
732     return;
733
734   do
735   {
736     running = 0;
737     mret = curl_multi_perform (plugin->curl_multi_handle, &running);
738
739     CURLMsg *msg;
740     int msgs_left;
741
742     while ((msg = curl_multi_info_read (plugin->curl_multi_handle, &msgs_left)))
743     {
744       CURL *easy_h = msg->easy_handle;
745       struct Session *s = NULL;
746       char *d = (char *) s;
747
748       if (easy_h == NULL)
749       {
750         GNUNET_break (0);
751         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
752                          "Client: connection to ended with reason %i: `%s', %i handles running\n",
753                          msg->data.result,
754                          curl_easy_strerror (msg->data.result), running);
755         continue;
756       }
757
758       GNUNET_assert (CURLE_OK ==
759                      curl_easy_getinfo (easy_h, CURLINFO_PRIVATE, &d));
760       s = (struct Session *) d;
761
762       if (GNUNET_YES != client_exist_session(plugin, s))
763       {
764         GNUNET_break (0);
765         return;
766       }
767
768       GNUNET_assert (s != NULL);
769       if (msg->msg == CURLMSG_DONE)
770       {
771         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
772                          "Client: %p connection to '%s'  %s ended with reason %i: `%s'\n",
773                          msg->easy_handle, GNUNET_i2s (&s->target),
774                          http_common_plugin_address_to_string (NULL, s->addr,
775                                                         s->addrlen),
776                          msg->data.result,
777                          curl_easy_strerror (msg->data.result));
778
779         /* Disconnect other transmission direction and tell transport */
780         client_disconnect (s);
781       }
782     }
783   }
784   while (mret == CURLM_CALL_MULTI_PERFORM);
785   client_schedule (plugin, GNUNET_NO);
786 }
787
788
789 static int
790 client_connect (struct Session *s)
791 {
792
793   struct HTTP_Client_Plugin *plugin = s->plugin;
794   int res = GNUNET_OK;
795   char *url;
796   CURLMcode mret;
797
798   /* create url */
799   if (NULL == http_common_plugin_address_to_string (NULL, s->addr, s->addrlen))
800   {
801     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
802                      "Invalid address peer `%s'\n",
803                      GNUNET_i2s (&s->target));
804     return GNUNET_SYSERR;
805   }
806
807   GNUNET_asprintf (&url, "%s%s;%u",
808       http_common_plugin_address_to_string (plugin, s->addr, s->addrlen),
809                    GNUNET_h2s_full (&plugin->env->my_identity->hashPubKey),
810                    plugin->last_tag);
811
812   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
813                    "Initiating outbound session peer `%s' using address `%s'\n",
814                    GNUNET_i2s (&s->target), url);
815
816   /* create get connection */
817   s->client_get = curl_easy_init ();
818 #if VERBOSE_CURL
819   curl_easy_setopt (s->client_get, CURLOPT_VERBOSE, 1L);
820   curl_easy_setopt (s->client_get, CURLOPT_DEBUGFUNCTION, &client_log);
821   curl_easy_setopt (s->client_get, CURLOPT_DEBUGDATA, s->client_get);
822 #endif
823 #if BUILD_HTTPS
824   curl_easy_setopt (s->client_get, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
825   curl_easy_setopt (s->client_get, CURLOPT_SSL_VERIFYPEER, 0);
826   curl_easy_setopt (s->client_get, CURLOPT_SSL_VERIFYHOST, 0);
827 #endif
828   curl_easy_setopt (s->client_get, CURLOPT_URL, url);
829   //curl_easy_setopt (s->client_get, CURLOPT_HEADERFUNCTION, &curl_get_header_cb);
830   //curl_easy_setopt (s->client_get, CURLOPT_WRITEHEADER, ps);
831   curl_easy_setopt (s->client_get, CURLOPT_READFUNCTION, client_send_cb);
832   curl_easy_setopt (s->client_get, CURLOPT_READDATA, s);
833   curl_easy_setopt (s->client_get, CURLOPT_WRITEFUNCTION, client_receive);
834   curl_easy_setopt (s->client_get, CURLOPT_WRITEDATA, s);
835   curl_easy_setopt (s->client_get, CURLOPT_TIMEOUT_MS,
836                     (long) GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value);
837   curl_easy_setopt (s->client_get, CURLOPT_PRIVATE, s);
838   curl_easy_setopt (s->client_get, CURLOPT_CONNECTTIMEOUT_MS,
839                     (long) HTTP_NOT_VALIDATED_TIMEOUT.rel_value);
840   curl_easy_setopt (s->client_get, CURLOPT_BUFFERSIZE,
841                     2 * GNUNET_SERVER_MAX_MESSAGE_SIZE);
842 #if CURL_TCP_NODELAY
843   curl_easy_setopt (ps->recv_endpoint, CURLOPT_TCP_NODELAY, 1);
844 #endif
845
846   /* create put connection */
847   s->client_put = curl_easy_init ();
848 #if VERBOSE_CURL
849   curl_easy_setopt (s->client_put, CURLOPT_VERBOSE, 1L);
850   curl_easy_setopt (s->client_put, CURLOPT_DEBUGFUNCTION, &client_log);
851   curl_easy_setopt (s->client_put, CURLOPT_DEBUGDATA, s->client_put);
852 #endif
853 #if BUILD_HTTPS
854   curl_easy_setopt (s->client_put, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
855   curl_easy_setopt (s->client_put, CURLOPT_SSL_VERIFYPEER, 0);
856   curl_easy_setopt (s->client_put, CURLOPT_SSL_VERIFYHOST, 0);
857 #endif
858   curl_easy_setopt (s->client_put, CURLOPT_URL, url);
859   curl_easy_setopt (s->client_put, CURLOPT_PUT, 1L);
860   //curl_easy_setopt (s->client_put, CURLOPT_HEADERFUNCTION, &curl_put_header_cb);
861   //curl_easy_setopt (s->client_put, CURLOPT_WRITEHEADER, ps);
862   curl_easy_setopt (s->client_put, CURLOPT_READFUNCTION, client_send_cb);
863   curl_easy_setopt (s->client_put, CURLOPT_READDATA, s);
864   curl_easy_setopt (s->client_put, CURLOPT_WRITEFUNCTION, client_receive);
865   curl_easy_setopt (s->client_put, CURLOPT_WRITEDATA, s);
866   curl_easy_setopt (s->client_put, CURLOPT_TIMEOUT_MS,
867                     (long) GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value);
868   curl_easy_setopt (s->client_put, CURLOPT_PRIVATE, s);
869   curl_easy_setopt (s->client_put, CURLOPT_CONNECTTIMEOUT_MS,
870                     (long) HTTP_NOT_VALIDATED_TIMEOUT.rel_value);
871   curl_easy_setopt (s->client_put, CURLOPT_BUFFERSIZE,
872                     2 * GNUNET_SERVER_MAX_MESSAGE_SIZE);
873 #if CURL_TCP_NODELAY
874   curl_easy_setopt (s->client_put, CURLOPT_TCP_NODELAY, 1);
875 #endif
876   GNUNET_free (url);
877
878   mret = curl_multi_add_handle (plugin->curl_multi_handle, s->client_get);
879   if (mret != CURLM_OK)
880   {
881     curl_easy_cleanup (s->client_get);
882     GNUNET_break (0);
883     return GNUNET_SYSERR;
884   }
885
886   mret = curl_multi_add_handle (plugin->curl_multi_handle, s->client_put);
887   if (mret != CURLM_OK)
888   {
889     curl_multi_remove_handle (plugin->curl_multi_handle, s->client_get);
890     curl_easy_cleanup (s->client_get);
891     curl_easy_cleanup (s->client_put);
892     GNUNET_break (0);
893     return GNUNET_SYSERR;
894   }
895
896   /* Perform connect */
897   plugin->cur_connections += 2;
898   GNUNET_STATISTICS_set (plugin->env->stats,
899       "# HTTP client connections",
900       plugin->cur_connections,
901       GNUNET_NO);
902
903   /* Re-schedule since handles have changed */
904   if (plugin->client_perform_task != GNUNET_SCHEDULER_NO_TASK)
905   {
906     GNUNET_SCHEDULER_cancel (plugin->client_perform_task);
907     plugin->client_perform_task = GNUNET_SCHEDULER_NO_TASK;
908   }
909   plugin->client_perform_task = GNUNET_SCHEDULER_add_now (client_run, plugin);
910   return res;
911 }
912
913 void
914 client_delete_session (struct Session *s)
915 {
916   struct HTTP_Client_Plugin *plugin = s->plugin;
917   struct HTTP_Message *pos = s->msg_head;
918   struct HTTP_Message *next = NULL;
919
920   client_stop_session_timeout (s);
921
922   GNUNET_CONTAINER_DLL_remove (plugin->head, plugin->tail, s);
923
924   while (NULL != (pos = next))
925   {
926     next = pos->next;
927     GNUNET_CONTAINER_DLL_remove (s->msg_head, s->msg_tail, pos);
928     if (pos->transmit_cont != NULL)
929       pos->transmit_cont (pos->transmit_cont_cls, &s->target, GNUNET_SYSERR);
930     GNUNET_free (pos);
931   }
932
933   if (s->msg_tk != NULL)
934   {
935     GNUNET_SERVER_mst_destroy (s->msg_tk);
936     s->msg_tk = NULL;
937   }
938   GNUNET_free (s->addr);
939   GNUNET_free (s);
940 }
941
942
943 /**
944  * Creates a new outbound session the transport service will use to send data to the
945  * peer
946  *
947  * @param cls the plugin
948  * @param address the address
949  * @return the session or NULL of max connections exceeded
950  */
951 static struct Session *
952 http_client_plugin_get_session (void *cls,
953                   const struct GNUNET_HELLO_Address *address)
954 {
955   struct HTTP_Client_Plugin *plugin = cls;
956   struct Session * s = NULL;
957
958   GNUNET_assert (plugin != NULL);
959   GNUNET_assert (address != NULL);
960   GNUNET_assert (address->address != NULL);
961
962
963   /* find existing session */
964   s = client_lookup_session (plugin, address);
965   if (s != NULL)
966     return s;
967
968   if (plugin->max_connections <= plugin->cur_connections)
969   {
970     GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, plugin->name,
971                      "Maximum number of connections (%u) reached: "
972                      "cannot connect to peer `%s'\n",
973                      plugin->max_connections,
974                      GNUNET_i2s (&address->peer));
975     return NULL;
976   }
977
978   s = GNUNET_malloc (sizeof (struct Session));
979   memcpy (&s->target, &address->peer, sizeof (struct GNUNET_PeerIdentity));
980   s->plugin = plugin;
981   s->addr = GNUNET_malloc (address->address_length);
982   memcpy (s->addr, address->address, address->address_length);
983   s->addrlen = address->address_length;
984   //s->ats_address_network_type = ats.value;
985   GNUNET_break (0);
986
987   client_start_session_timeout (s);
988
989   /* add new session */
990   GNUNET_CONTAINER_DLL_insert (plugin->head, plugin->tail, s);
991
992   /* initiate new connection */
993   if (GNUNET_SYSERR == client_connect (s))
994   {
995     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
996                      "Cannot connect to peer `%s' address `%s''\n",
997                      http_common_plugin_address_to_string (NULL, s->addr, s->addrlen),
998                      GNUNET_i2s (&s->target));
999     client_delete_session (s);
1000     return NULL;
1001   }
1002   return s;
1003 }
1004
1005 static int
1006 client_start (struct HTTP_Client_Plugin *plugin)
1007 {
1008   curl_global_init (CURL_GLOBAL_ALL);
1009   plugin->curl_multi_handle = curl_multi_init ();
1010
1011   if (NULL == plugin->curl_multi_handle)
1012   {
1013     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
1014                      _("Could not initialize curl multi handle, failed to start %s plugin!\n"),
1015                      plugin->name);
1016     return GNUNET_SYSERR;
1017   }
1018   return GNUNET_OK;
1019 }
1020
1021 /**
1022  * Session was idle, so disconnect it
1023  */
1024 static void
1025 client_session_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1026 {
1027   GNUNET_assert (NULL != cls);
1028   struct Session *s = cls;
1029
1030   s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1031   GNUNET_log (TIMEOUT_LOG,
1032               "Session %p was idle for %llu ms, disconnecting\n",
1033               s, (unsigned long long) TIMEOUT.rel_value);
1034
1035   /* call session destroy function */
1036   GNUNET_assert (GNUNET_OK == client_disconnect (s));
1037 }
1038
1039 /**
1040 * Start session timeout
1041 */
1042 static void
1043 client_start_session_timeout (struct Session *s)
1044 {
1045
1046  GNUNET_assert (NULL != s);
1047  GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == s->timeout_task);
1048  s->timeout_task =  GNUNET_SCHEDULER_add_delayed (TIMEOUT,
1049                                                   &client_session_timeout,
1050                                                   s);
1051  GNUNET_log (TIMEOUT_LOG,
1052              "Timeout for session %p set to %llu ms\n",
1053              s,  (unsigned long long) TIMEOUT.rel_value);
1054  GNUNET_break (0);
1055 }
1056
1057 /**
1058 * Increment session timeout due to activity
1059 */
1060 static void
1061 client_reschedule_session_timeout (struct Session *s)
1062 {
1063
1064  GNUNET_assert (NULL != s);
1065  GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != s->timeout_task);
1066
1067  GNUNET_SCHEDULER_cancel (s->timeout_task);
1068  s->timeout_task =  GNUNET_SCHEDULER_add_delayed (TIMEOUT,
1069                                                   &client_session_timeout,
1070                                                   s);
1071  GNUNET_log (TIMEOUT_LOG,
1072              "Timeout rescheduled for session %p set to %llu ms\n",
1073              s, (unsigned long long) TIMEOUT.rel_value);
1074  GNUNET_break (0);
1075 }
1076
1077 /**
1078 * Cancel timeout
1079 */
1080 static void
1081 client_stop_session_timeout (struct Session *s)
1082 {
1083  GNUNET_assert (NULL != s);
1084
1085  if (GNUNET_SCHEDULER_NO_TASK != s->timeout_task)
1086  {
1087    GNUNET_SCHEDULER_cancel (s->timeout_task);
1088    s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1089    GNUNET_log (TIMEOUT_LOG, "Timeout stopped for session %p\n", s);
1090  }
1091 }
1092
1093
1094 /**
1095  * Another peer has suggested an address for this
1096  * peer and transport plugin.  Check that this could be a valid
1097  * address.  If so, consider adding it to the list
1098  * of addresses.
1099  *
1100  * @param cls closure
1101  * @param addr pointer to the address
1102  * @param addrlen length of addr
1103  * @return GNUNET_OK if this is a plausible address for this peer
1104  *         and transport
1105  */
1106 static int
1107 http_client_plugin_address_suggested (void *cls, const void *addr, size_t addrlen)
1108 {
1109   /* struct Plugin *plugin = cls; */
1110
1111   /* A HTTP/S client does not have any valid address so:*/
1112   return GNUNET_NO;
1113 }
1114
1115 /**
1116  * Exit point from the plugin.
1117  */
1118 void *
1119 LIBGNUNET_PLUGIN_TRANSPORT_DONE (void *cls)
1120 {
1121   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1122   struct HTTP_Client_Plugin *plugin = api->cls;
1123
1124   if (NULL == api->cls)
1125   {
1126     GNUNET_free (api);
1127     return NULL;
1128   }
1129
1130   if (NULL != plugin->curl_multi_handle)
1131   {
1132     curl_multi_cleanup (plugin->curl_multi_handle);
1133     plugin->curl_multi_handle = NULL;
1134   }
1135   curl_global_cleanup ();
1136
1137   GNUNET_free (plugin);
1138   GNUNET_free (api);
1139   return NULL;
1140 }
1141
1142
1143 static int
1144 client_configure_plugin (struct HTTP_Client_Plugin *plugin)
1145 {
1146   unsigned long long max_connections;
1147
1148   /* Optional parameters */
1149   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (plugin->env->cfg,
1150                       plugin->name,
1151                       "MAX_CONNECTIONS", &max_connections))
1152     max_connections = 128;
1153   plugin->max_connections = max_connections;
1154
1155   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1156                    _("Maximum number of connections is %u\n"),
1157                    plugin->max_connections);
1158   return GNUNET_OK;
1159 }
1160
1161 /**
1162  * Entry point for the plugin.
1163  */
1164 void *
1165 LIBGNUNET_PLUGIN_TRANSPORT_INIT (void *cls)
1166 {
1167   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1168   struct GNUNET_TRANSPORT_PluginFunctions *api;
1169   struct HTTP_Client_Plugin *plugin;
1170
1171   if (NULL == env->receive)
1172   {
1173     /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
1174        initialze the plugin or the API */
1175     api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1176     api->cls = NULL;
1177     api->address_to_string = &http_common_plugin_address_to_string;
1178     api->string_to_address = &http_common_plugin_string_to_address;
1179     api->address_pretty_printer = &http_common_plugin_address_pretty_printer;
1180     return api;
1181   }
1182
1183   plugin = GNUNET_malloc (sizeof (struct HTTP_Client_Plugin));
1184   p = plugin;
1185   plugin->env = env;
1186   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1187   api->cls = plugin;
1188   api->send = &http_client_plugin_send;
1189   api->disconnect = &http_client_plugin_disconnect;
1190   api->check_address = &http_client_plugin_address_suggested;
1191   api->get_session = &http_client_plugin_get_session;
1192   api->address_to_string = &http_common_plugin_address_to_string;
1193   api->string_to_address = &http_common_plugin_string_to_address;
1194   api->address_pretty_printer = &http_common_plugin_address_pretty_printer;
1195
1196
1197 #if BUILD_HTTPS
1198   plugin->name = "transport-https_client";
1199   plugin->protocol = "https";
1200 #else
1201   plugin->name = "transport-http_client";
1202   plugin->protocol = "http";
1203 #endif
1204
1205   if (GNUNET_SYSERR == client_configure_plugin (plugin))
1206   {
1207       LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
1208       return NULL;
1209   }
1210
1211   /* Start client */
1212   if (GNUNET_SYSERR == client_start (plugin))
1213   {
1214       LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
1215       return NULL;
1216   }
1217   return api;
1218 }
1219
1220 /* end of plugin_transport_http_client.c */