- 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 #define VERBOSE_CURL GNUNET_YES
36
37 #define PUT_DISCONNECT_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
38
39 #define ENABLE_PUT GNUNET_YES
40 #define ENABLE_GET GNUNET_YES
41
42 #include "platform.h"
43 #include "gnunet_protocols.h"
44 #include "gnunet_common.h"
45 #include "gnunet_server_lib.h"
46 #include "gnunet_transport_plugin.h"
47 #include "plugin_transport_http_common.h"
48 #include <curl/curl.h>
49
50
51 /**
52  * Encapsulation of all of the state of the plugin.
53  */
54 struct HTTP_Client_Plugin;
55
56
57 /**
58  *  Message to send using http
59  */
60 struct HTTP_Message
61 {
62   /**
63    * next pointer for double linked list
64    */
65   struct HTTP_Message *next;
66
67   /**
68    * previous pointer for double linked list
69    */
70   struct HTTP_Message *prev;
71
72   /**
73    * buffer containing data to send
74    */
75   char *buf;
76
77   /**
78    * amount of data already sent
79    */
80   size_t pos;
81
82   /**
83    * buffer length
84    */
85   size_t size;
86
87   /**
88    * Continuation function to call once the transmission buffer
89    * has again space available.  NULL if there is no
90    * continuation to call.
91    */
92   GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
93
94   /**
95    * Closure for transmit_cont.
96    */
97   void *transmit_cont_cls;
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    * The URL to connect to
123    */
124   char *url;
125
126   /**
127    * Address
128    */
129   void *addr;
130
131   /**
132    * Address length
133    */
134   size_t addrlen;
135
136   /**
137    * ATS network type in NBO
138    */
139   uint32_t ats_address_network_type;
140
141   /**
142    * Pointer to the global plugin struct.
143    */
144   struct HTTP_Client_Plugin *plugin;
145
146   /**
147    * Was session given to transport service?
148    */
149  // int session_passed;
150
151   /**
152    * Client send handle
153    */
154   void *client_put;
155
156
157   /**
158    * Is the client PUT handle currently paused
159    */
160   int put_paused;
161
162   /**
163    * Is the client PUT handle disconnect in progress?
164    */
165   int put_tmp_disconnecting;
166
167   /**
168    * Is the client PUT handle temporarily disconnected?
169    */
170   int put_tmp_disconnected;
171
172   /**
173    * Client receive handle
174    */
175   void *client_get;
176
177   /**
178    * next pointer for double linked list
179    */
180   struct HTTP_Message *msg_head;
181
182   /**
183    * previous pointer for double linked list
184    */
185   struct HTTP_Message *msg_tail;
186
187   /**
188    * Message stream tokenizer for incoming data
189    */
190   struct GNUNET_SERVER_MessageStreamTokenizer *msg_tk;
191
192   /**
193    * Session timeout task
194    */
195   GNUNET_SCHEDULER_TaskIdentifier put_disconnect_task;
196
197   /**
198    * Session timeout task
199    */
200   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
201
202   /**
203    * Task to wake up client receive handle when receiving is allowed again
204    */
205   GNUNET_SCHEDULER_TaskIdentifier recv_wakeup_task;
206
207   /**
208   * Absolute time when to receive data again
209   * Used for receive throttling
210   */
211  struct GNUNET_TIME_Absolute next_receive;
212 };
213
214
215 /**
216  * Encapsulation of all of the state of the plugin.
217  */
218 struct HTTP_Client_Plugin
219 {
220   /**
221    * Our environment.
222    */
223   struct GNUNET_TRANSPORT_PluginEnvironment *env;
224
225   /**
226    * Linked list head of open sessions.
227    */
228   struct Session *head;
229
230   /**
231    * Linked list tail of open sessions.
232    */
233   struct Session *tail;
234
235   /**
236    * Plugin name
237    */
238   char *name;
239
240   /**
241    * Protocol
242    */
243   char *protocol;
244
245   /**
246    * Maximum number of sockets the plugin can use
247    * Each http inbound /outbound connections are two connections
248    */
249   unsigned int max_connections;
250
251   /**
252    * Current number of sockets the plugin can use
253    * Each http inbound /outbound connections are two connections
254    */
255   unsigned int cur_connections;
256
257   /**
258    * Last used unique HTTP connection tag
259    */
260   uint32_t last_tag;
261
262   /**
263    * use IPv6
264    */
265   uint16_t use_ipv6;
266
267   /**
268    * use IPv4
269    */
270   uint16_t use_ipv4;
271
272   /**
273    * cURL Multihandle
274    */
275   CURLM *curl_multi_handle;
276
277   /**
278    * curl perform task
279    */
280   GNUNET_SCHEDULER_TaskIdentifier client_perform_task;
281 };
282
283
284 /**
285  * Encapsulation of all of the state of the plugin.
286  */
287 struct HTTP_Client_Plugin *p;
288
289
290 /**
291  * Start session timeout for a session
292  * @param s the session
293  */
294 static void
295 client_start_session_timeout (struct Session *s);
296
297
298 /**
299  * Increment session timeout due to activity for a session
300  * @param s the session
301  */
302 static void
303 client_reschedule_session_timeout (struct Session *s);
304
305
306 /**
307  * Cancel timeout for a session
308  * @param s the session
309  */
310 static void
311 client_stop_session_timeout (struct Session *s);
312
313
314 /**
315  * Function setting up file descriptors and scheduling task to run
316  *
317  * @param  plugin plugin as closure
318  * @param now schedule task in 1ms, regardless of what curl may say
319  * @return GNUNET_SYSERR for hard failure, GNUNET_OK for ok
320  */
321 static int
322 client_schedule (struct HTTP_Client_Plugin *plugin, int now);
323
324 static int
325 client_connect_put (struct Session *s);
326
327 /**
328  * Does a session s exists?
329  *
330  * @param plugin the plugin
331  * @param s desired session
332  * @return GNUNET_YES or GNUNET_NO
333  */
334 static int
335 client_exist_session (struct HTTP_Client_Plugin *plugin, struct Session *s)
336 {
337   struct Session * head;
338
339   GNUNET_assert (NULL != plugin);
340   GNUNET_assert (NULL != s);
341
342   for (head = plugin->head; head != NULL; head = head->next)
343   {
344     if (head == s)
345       return GNUNET_YES;
346   }
347   return GNUNET_NO;
348 }
349
350 #if VERBOSE_CURL
351 /**
352  * Function to log curl debug messages with GNUNET_log
353  *
354  * @param curl handle
355  * @param type curl_infotype
356  * @param data data
357  * @param size size
358  * @param cls  closure
359  * @return 0
360  */
361 static int
362 client_log (CURL * curl, curl_infotype type, char *data, size_t size, void *cls)
363 {
364   char *ttype;
365   if ((type == CURLINFO_TEXT) || (type == CURLINFO_HEADER_IN) || (type == CURLINFO_HEADER_OUT))
366   {
367     char text[size + 2];
368
369     switch (type) {
370       case CURLINFO_TEXT:
371         ttype = "TEXT";
372         break;
373       case CURLINFO_HEADER_IN:
374         ttype = "HEADER_IN";
375         break;
376       case CURLINFO_HEADER_OUT:
377         ttype = "HEADER_OUT";
378         break;
379       default:
380         break;
381     }
382
383     memcpy (text, data, size);
384     if (text[size - 1] == '\n')
385       text[size] = '\0';
386     else
387     {
388       text[size] = '\n';
389       text[size + 1] = '\0';
390     }
391 #if BUILD_HTTPS
392     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "transport-https_client",
393                      "Connection %p %s: %s", cls, ttype, text);
394 #else
395     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "transport-http_client",
396                      "Connection %p %s: %s", cls, ttype, text);
397 #endif
398   }
399   return 0;
400 }
401 #endif
402
403
404 /**
405  * Function that can be used by the transport service to transmit
406  * a message using the plugin.   Note that in the case of a
407  * peer disconnecting, the continuation MUST be called
408  * prior to the disconnect notification itself.  This function
409  * will be called with this peer's HELLO message to initiate
410  * a fresh connection to another peer.
411  *
412  * @param cls closure
413  * @param session which session must be used
414  * @param msgbuf the message to transmit
415  * @param msgbuf_size number of bytes in 'msgbuf'
416  * @param priority how important is the message (most plugins will
417  *                 ignore message priority and just FIFO)
418  * @param to how long to wait at most for the transmission (does not
419  *                require plugins to discard the message after the timeout,
420  *                just advisory for the desired delay; most plugins will ignore
421  *                this as well)
422  * @param cont continuation to call once the message has
423  *        been transmitted (or if the transport is ready
424  *        for the next transmission call; or if the
425  *        peer disconnected...); can be NULL
426  * @param cont_cls closure for cont
427  * @return number of bytes used (on the physical network, with overheads);
428  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
429  *         and does NOT mean that the message was not transmitted (DV)
430  */
431 static ssize_t
432 http_client_plugin_send (void *cls,
433                   struct Session *s,
434                   const char *msgbuf, size_t msgbuf_size,
435                   unsigned int priority,
436                   struct GNUNET_TIME_Relative to,
437                   GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
438 {
439   struct HTTP_Client_Plugin *plugin = cls;
440   struct HTTP_Message *msg;
441
442   GNUNET_assert (plugin != NULL);
443   GNUNET_assert (s != NULL);
444
445   /* lookup if session is really existing */
446   if (GNUNET_YES != client_exist_session (plugin, s))
447   {
448     GNUNET_break (0);
449     return GNUNET_SYSERR;
450   }
451
452   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, s->plugin->name,
453                    "Session %p/connection %p: Sending message with %u to peer `%s' with \n",
454                    s, s->client_put,
455                    msgbuf_size, GNUNET_i2s (&s->target));
456
457   /* create new message and schedule */
458   msg = GNUNET_malloc (sizeof (struct HTTP_Message) + msgbuf_size);
459   msg->next = NULL;
460   msg->size = msgbuf_size;
461   msg->pos = 0;
462   msg->buf = (char *) &msg[1];
463   msg->transmit_cont = cont;
464   msg->transmit_cont_cls = cont_cls;
465   memcpy (msg->buf, msgbuf, msgbuf_size);
466   GNUNET_CONTAINER_DLL_insert_tail (s->msg_head, s->msg_tail, msg);
467
468   if (GNUNET_YES == s->put_tmp_disconnected)
469   {
470       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, s->plugin->name,
471                        "Session %p: Reconnecting PUT connection\n",
472                        s);
473       s->put_tmp_disconnected = GNUNET_NO;
474       if (GNUNET_SYSERR == client_connect_put (s))
475       {
476         return GNUNET_SYSERR;
477       }
478   }
479
480   if (GNUNET_YES == s->put_paused)
481   {
482     GNUNET_assert (s->put_disconnect_task != GNUNET_SCHEDULER_NO_TASK);
483     GNUNET_SCHEDULER_cancel (s->put_disconnect_task);
484     s->put_disconnect_task = GNUNET_SCHEDULER_NO_TASK;
485     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, s->plugin->name,
486                      "Session %p/connection %p: unpausing connection\n",
487                      s, s->client_put);
488     s->put_paused = GNUNET_NO;
489     curl_easy_pause (s->client_put, CURLPAUSE_CONT);
490   }
491   client_schedule (s->plugin, GNUNET_YES);
492   client_reschedule_session_timeout (s);
493   return msgbuf_size;
494 }
495
496
497 /**
498  * Delete session s
499  *
500  * @param s the session to delete
501  */
502 static void
503 client_delete_session (struct Session *s)
504 {
505   struct HTTP_Client_Plugin *plugin = s->plugin;
506   struct HTTP_Message *pos;
507   struct HTTP_Message *next;
508
509   client_stop_session_timeout (s);
510
511   if (GNUNET_SCHEDULER_NO_TASK != s->put_disconnect_task)
512   {
513       GNUNET_SCHEDULER_cancel (s->put_disconnect_task);
514       s->put_disconnect_task = GNUNET_SCHEDULER_NO_TASK;
515   }
516
517   GNUNET_CONTAINER_DLL_remove (plugin->head, plugin->tail, s);
518
519   next = s->msg_head;
520   while (NULL != (pos = next))
521   {
522     next = pos->next;
523     GNUNET_CONTAINER_DLL_remove (s->msg_head, s->msg_tail, pos);
524     if (pos->transmit_cont != NULL)
525       pos->transmit_cont (pos->transmit_cont_cls, &s->target, GNUNET_SYSERR);
526     GNUNET_free (pos);
527   }
528
529   if (s->msg_tk != NULL)
530   {
531     GNUNET_SERVER_mst_destroy (s->msg_tk);
532     s->msg_tk = NULL;
533   }
534   GNUNET_free (s->addr);
535   GNUNET_free (s->url);
536   GNUNET_free (s);
537 }
538
539
540
541 /**
542  * Disconnect a session
543  *
544  * @param s session
545  * @return GNUNET_OK on success, GNUNET_SYSERR on error
546  */
547 static int
548 client_disconnect (struct Session *s)
549 {
550   struct HTTP_Client_Plugin *plugin = s->plugin;
551   struct HTTP_Message *msg;
552   struct HTTP_Message *t;
553   int res = GNUNET_OK;
554   CURLMcode mret;
555
556   if (GNUNET_YES != client_exist_session (plugin, s))
557   {
558     GNUNET_break (0);
559     return GNUNET_SYSERR;
560   }
561
562   if (s->client_put != NULL)
563   {
564     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
565                      "Session %p/connection %p: disconnecting PUT connection to peer `%s'\n",
566                      s, s->client_put, GNUNET_i2s (&s->target));
567
568     /* remove curl handle from multi handle */
569     mret = curl_multi_remove_handle (plugin->curl_multi_handle, s->client_put);
570     if (mret != CURLM_OK)
571     {
572       /* clean up easy handle, handle is now invalid and free'd */
573       res = GNUNET_SYSERR;
574       GNUNET_break (0);
575     }
576     curl_easy_cleanup (s->client_put);
577     s->client_put = NULL;
578   }
579
580
581   if (s->recv_wakeup_task != GNUNET_SCHEDULER_NO_TASK)
582   {
583     GNUNET_SCHEDULER_cancel (s->recv_wakeup_task);
584     s->recv_wakeup_task = GNUNET_SCHEDULER_NO_TASK;
585   }
586
587   if (s->client_get != NULL)
588   {
589       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
590                        "Session %p/connection %p: disconnecting GET connection to peer `%s'\n",
591                        s, s->client_get, GNUNET_i2s (&s->target));
592
593     /* remove curl handle from multi handle */
594     mret = curl_multi_remove_handle (plugin->curl_multi_handle, s->client_get);
595     if (mret != CURLM_OK)
596     {
597       /* clean up easy handle, handle is now invalid and free'd */
598       res = GNUNET_SYSERR;
599       GNUNET_break (0);
600     }
601     curl_easy_cleanup (s->client_get);
602     s->client_get = NULL;
603   }
604
605   msg = s->msg_head;
606   while (msg != NULL)
607   {
608     t = msg->next;
609     if (NULL != msg->transmit_cont)
610       msg->transmit_cont (msg->transmit_cont_cls, &s->target, GNUNET_SYSERR);
611     GNUNET_CONTAINER_DLL_remove (s->msg_head, s->msg_tail, msg);
612     GNUNET_free (msg);
613     msg = t;
614   }
615
616   GNUNET_assert (plugin->cur_connections >= 2);
617   plugin->cur_connections -= 2;
618   GNUNET_STATISTICS_set (plugin->env->stats,
619       "# HTTP client sessions",
620       plugin->cur_connections,
621       GNUNET_NO);
622
623   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
624                    "Session %p: notifying transport about ending session\n",s);
625
626   plugin->env->session_end (plugin->env->cls, &s->target, s);
627   client_delete_session (s);
628
629   /* Re-schedule since handles have changed */
630   if (plugin->client_perform_task != GNUNET_SCHEDULER_NO_TASK)
631   {
632     GNUNET_SCHEDULER_cancel (plugin->client_perform_task);
633     plugin->client_perform_task = GNUNET_SCHEDULER_NO_TASK;
634   }
635   client_schedule (plugin, GNUNET_YES);
636
637   return res;
638 }
639
640
641 /**
642  * Function that can be used to force the plugin to disconnect
643  * from the given peer and cancel all previous transmissions
644  * (and their continuationc).
645  *
646  * @param cls closure
647  * @param target peer from which to disconnect
648  */
649 static void
650 http_client_plugin_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
651 {
652   struct HTTP_Client_Plugin *plugin = cls;
653   struct Session *next = NULL;
654   struct Session *pos = NULL;
655
656   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
657                    "Transport tells me to disconnect `%s'\n",
658                    GNUNET_i2s (target));
659
660   next = plugin->head;
661   while (NULL != (pos = next))
662   {
663     next = pos->next;
664     if (0 == memcmp (target, &pos->target, sizeof (struct GNUNET_PeerIdentity)))
665     {
666       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
667                        "Disconnecting session %p to `%pos'\n",
668                        pos, GNUNET_i2s (target));
669       GNUNET_assert (GNUNET_OK == client_disconnect (pos));
670     }
671   }
672
673 }
674
675
676 static struct Session *
677 client_lookup_session (struct HTTP_Client_Plugin *plugin,
678                        const struct GNUNET_HELLO_Address *address)
679 {
680   struct Session *pos;
681
682   for (pos = plugin->head; NULL != pos; pos = pos->next)
683     if ((0 == memcmp (&address->peer, &pos->target, sizeof (struct GNUNET_PeerIdentity))) &&
684         (address->address_length == pos->addrlen) &&
685         (0 == memcmp (address->address, pos->addr, pos->addrlen)))
686       return pos;
687   return NULL;
688 }
689
690 static void
691 client_put_disconnect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
692 {
693   struct Session *s = cls;
694   s->put_disconnect_task = GNUNET_SCHEDULER_NO_TASK;
695   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, s->plugin->name,
696                    "Session %p/connection %p: will be disconnected due to no activity\n",
697                    s, s->client_put);
698   s->put_paused = GNUNET_NO;
699   s->put_tmp_disconnecting = GNUNET_YES;
700   curl_easy_pause (s->client_put, CURLPAUSE_CONT);
701   client_schedule (s->plugin, GNUNET_YES);
702 }
703
704
705
706 /**
707  * Callback method used with libcurl
708  * Method is called when libcurl needs to read data during sending
709  *
710  * @param stream pointer where to write data
711  * @param size size of an individual element
712  * @param nmemb count of elements that can be written to the buffer
713  * @param cls source pointer, passed to the libcurl handle
714  * @return bytes written to stream, returning 0 will terminate connection!
715  */
716 static size_t
717 client_send_cb (void *stream, size_t size, size_t nmemb, void *cls)
718 {
719   struct Session *s = cls;
720   struct HTTP_Client_Plugin *plugin = s->plugin;
721   struct HTTP_Message *msg = s->msg_head;
722   size_t len;
723
724   if (GNUNET_YES != client_exist_session (plugin, s))
725   {
726     GNUNET_break (0);
727     return 0;
728   }
729   if (GNUNET_YES == s->put_tmp_disconnecting)
730   {
731
732       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, s->plugin->name,
733                        "Session %p/connection %p: disconnect due to inactivity\n",
734                        s, s->client_put);
735       s->put_tmp_disconnecting = GNUNET_NO;
736       s->put_tmp_disconnected = GNUNET_YES;
737       return 0;
738   }
739
740   if (NULL == msg)
741   {
742     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
743                      "Session %p/connection %p: nothing to send, suspending\n",
744                      s, s->client_put);
745     s->put_disconnect_task = GNUNET_SCHEDULER_add_delayed (PUT_DISCONNECT_TIMEOUT, &client_put_disconnect, s);
746     s->put_paused = GNUNET_YES;
747     return CURL_READFUNC_PAUSE;
748   }
749   /* data to send */
750   GNUNET_assert (msg->pos < msg->size);
751   /* calculate how much fits in buffer */
752   len = GNUNET_MIN (msg->size - msg->pos,
753                     size * nmemb);
754   memcpy (stream, &msg->buf[msg->pos], len);
755   msg->pos += len;
756   if (msg->pos == msg->size)
757   {
758     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
759                      "Session %p/connection %p: sent message with %u bytes sent, removing message from queue\n",
760                      s, s->client_put, msg->size, msg->pos);
761     /* Calling transmit continuation  */
762     GNUNET_CONTAINER_DLL_remove (s->msg_head, s->msg_tail, msg);
763     if (NULL != msg->transmit_cont)
764       msg->transmit_cont (msg->transmit_cont_cls, &s->target, GNUNET_OK);
765     GNUNET_free (msg);
766   }
767   client_reschedule_session_timeout (s);
768   return len;
769 }
770
771
772 /**
773  * Wake up a curl handle which was suspended
774  *
775  * @param cls the session
776  * @param tc task context
777  */
778 static void
779 client_wake_up (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
780 {
781   struct Session *s = cls;
782
783   if (GNUNET_YES != client_exist_session(p, s))
784   {
785     GNUNET_break (0);
786     return;
787   }
788   s->recv_wakeup_task = GNUNET_SCHEDULER_NO_TASK;
789   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
790     return;
791   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, s->plugin->name,
792                    "Session %p/connection %p: Waking up GET handle\n", s, s->client_get);
793   if (s->client_get != NULL)
794     curl_easy_pause (s->client_get, CURLPAUSE_CONT);
795 }
796
797
798 /**
799  * Callback for message stream tokenizer
800  *
801  * @param cls the session
802  * @param client not used
803  * @param message the message received
804  * @return always GNUNET_OK
805  */
806 static int
807 client_receive_mst_cb (void *cls, void *client,
808                        const struct GNUNET_MessageHeader *message)
809 {
810   struct Session *s = cls;
811   struct HTTP_Client_Plugin *plugin;
812   struct GNUNET_TIME_Relative delay;
813   struct GNUNET_ATS_Information atsi[2];
814   if (GNUNET_YES != client_exist_session(p, s))
815   {
816     GNUNET_break (0);
817     return GNUNET_OK;
818   }
819   plugin = s->plugin;
820
821   atsi[0].type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
822   atsi[0].value = htonl (1);
823   atsi[1].type = htonl (GNUNET_ATS_NETWORK_TYPE);
824   atsi[1].value = s->ats_address_network_type;
825   GNUNET_break (s->ats_address_network_type != ntohl (GNUNET_ATS_NET_UNSPECIFIED));
826
827   delay = s->plugin->env->receive (plugin->env->cls, &s->target, message,
828                                    (const struct GNUNET_ATS_Information *) &atsi, 2,
829                                    s, s->addr, s->addrlen);
830
831   s->next_receive =
832       GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (), delay);
833
834   if (GNUNET_TIME_absolute_get ().abs_value < s->next_receive.abs_value)
835   {
836
837     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
838                      "Client: peer `%s' address `%s' next read delayed for %llu ms\n",
839                      GNUNET_i2s (&s->target), GNUNET_a2s (s->addr, s->addrlen),
840                      delay);
841   }
842   client_reschedule_session_timeout (s);
843   return GNUNET_OK;
844 }
845
846
847 /**
848  * Callback method used with libcurl when data for a PUT connection are
849  * received. We do not expect data here, so we just dismiss it
850  *
851  * @param stream pointer where to write data
852  * @param size size of an individual element
853  * @param nmemb count of elements that can be written to the buffer
854  * @param cls destination pointer, passed to the libcurl handle
855  * @return bytes read from stream
856  */
857 static size_t
858 client_receive_put (void *stream, size_t size, size_t nmemb, void *cls)
859 {
860   return size * nmemb;
861 }
862
863
864 /**
865  * Callback method used with libcurl when data for a GET connection are
866  * received. Forward to MST
867  *
868  * @param stream pointer where to write data
869  * @param size size of an individual element
870  * @param nmemb count of elements that can be written to the buffer
871  * @param cls destination pointer, passed to the libcurl handle
872  * @return bytes read from stream
873  */
874 static size_t
875 client_receive (void *stream, size_t size, size_t nmemb, void *cls)
876 {
877   struct Session *s = cls;
878   struct GNUNET_TIME_Absolute now;
879   size_t len = size * nmemb;
880   struct HTTP_Client_Plugin *plugin = s->plugin;
881
882   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
883                    "Received %u bytes from peer `%s'\n", len,
884                    GNUNET_i2s (&s->target));
885   now = GNUNET_TIME_absolute_get ();
886   if (now.abs_value < s->next_receive.abs_value)
887   {
888     struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
889     struct GNUNET_TIME_Relative delta =
890         GNUNET_TIME_absolute_get_difference (now, s->next_receive);
891     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
892                      "No inbound bandwidth for session %p available! Next read was delayed for %llu ms\n",
893                      s, delta.rel_value);
894     if (s->recv_wakeup_task != GNUNET_SCHEDULER_NO_TASK)
895     {
896       GNUNET_SCHEDULER_cancel (s->recv_wakeup_task);
897       s->recv_wakeup_task = GNUNET_SCHEDULER_NO_TASK;
898     }
899     s->recv_wakeup_task =
900         GNUNET_SCHEDULER_add_delayed (delta, &client_wake_up, s);
901     return CURLPAUSE_ALL;
902   }
903   if (NULL == s->msg_tk)
904     s->msg_tk = GNUNET_SERVER_mst_create (&client_receive_mst_cb, s);
905   GNUNET_SERVER_mst_receive (s->msg_tk, s, stream, len, GNUNET_NO, GNUNET_NO);
906   return len;
907 }
908
909
910 /**
911  * Task performing curl operations
912  *
913  * @param cls plugin as closure
914  * @param tc gnunet scheduler task context
915  */
916 static void
917 client_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
918
919
920 /**
921  * Function setting up file descriptors and scheduling task to run
922  *
923  * @param  plugin plugin as closure
924  * @param now schedule task in 1ms, regardless of what curl may say
925  * @return GNUNET_SYSERR for hard failure, GNUNET_OK for ok
926  */
927 static int
928 client_schedule (struct HTTP_Client_Plugin *plugin, int now)
929 {
930   fd_set rs;
931   fd_set ws;
932   fd_set es;
933   int max;
934   struct GNUNET_NETWORK_FDSet *grs;
935   struct GNUNET_NETWORK_FDSet *gws;
936   long to;
937   CURLMcode mret;
938   struct GNUNET_TIME_Relative timeout;
939
940   /* Cancel previous scheduled task */
941   if (plugin->client_perform_task != GNUNET_SCHEDULER_NO_TASK)
942   {
943     GNUNET_SCHEDULER_cancel (plugin->client_perform_task);
944     plugin->client_perform_task = GNUNET_SCHEDULER_NO_TASK;
945   }
946   max = -1;
947   FD_ZERO (&rs);
948   FD_ZERO (&ws);
949   FD_ZERO (&es);
950   mret = curl_multi_fdset (plugin->curl_multi_handle, &rs, &ws, &es, &max);
951   if (mret != CURLM_OK)
952   {
953     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("%s failed at %s:%d: `%s'\n"),
954                 "curl_multi_fdset", __FILE__, __LINE__,
955                 curl_multi_strerror (mret));
956     return GNUNET_SYSERR;
957   }
958   mret = curl_multi_timeout (plugin->curl_multi_handle, &to);
959   if (to == -1)
960     timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1);
961   else
962     timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, to);
963   if (now == GNUNET_YES)
964     timeout = GNUNET_TIME_UNIT_MILLISECONDS;
965
966   if (mret != CURLM_OK)
967   {
968     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("%s failed at %s:%d: `%s'\n"),
969                 "curl_multi_timeout", __FILE__, __LINE__,
970                 curl_multi_strerror (mret));
971     return GNUNET_SYSERR;
972   }
973
974   grs = GNUNET_NETWORK_fdset_create ();
975   gws = GNUNET_NETWORK_fdset_create ();
976   GNUNET_NETWORK_fdset_copy_native (grs, &rs, max + 1);
977   GNUNET_NETWORK_fdset_copy_native (gws, &ws, max + 1);
978
979   plugin->client_perform_task =
980       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
981                                    timeout, grs, gws,
982                                    &client_run, plugin);
983   GNUNET_NETWORK_fdset_destroy (gws);
984   GNUNET_NETWORK_fdset_destroy (grs);
985   return GNUNET_OK;
986 }
987
988
989 /**
990  * Task performing curl operations
991  *
992  * @param cls plugin as closure
993  * @param tc gnunet scheduler task context
994  */
995 static void
996 client_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
997 {
998   struct HTTP_Client_Plugin *plugin = cls;
999   int running;
1000   int http_statuscode;
1001   CURLMcode mret;
1002
1003   GNUNET_assert (cls != NULL);
1004
1005   plugin->client_perform_task = GNUNET_SCHEDULER_NO_TASK;
1006   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1007     return;
1008
1009   do
1010   {
1011     running = 0;
1012     mret = curl_multi_perform (plugin->curl_multi_handle, &running);
1013
1014     CURLMsg *msg;
1015     int msgs_left;
1016
1017     while ((msg = curl_multi_info_read (plugin->curl_multi_handle, &msgs_left)))
1018     {
1019       CURL *easy_h = msg->easy_handle;
1020       struct Session *s = NULL;
1021       char *d = (char *) s;
1022
1023       if (easy_h == NULL)
1024       {
1025         GNUNET_break (0);
1026         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1027                          "Client: connection to ended with reason %i: `%s', %i handles running\n",
1028                          msg->data.result,
1029                          curl_easy_strerror (msg->data.result), running);
1030         continue;
1031       }
1032
1033       GNUNET_assert (CURLE_OK ==
1034                      curl_easy_getinfo (easy_h, CURLINFO_PRIVATE, &d));
1035       s = (struct Session *) d;
1036
1037       if (GNUNET_YES != client_exist_session(plugin, s))
1038       {
1039         GNUNET_break (0);
1040         return;
1041       }
1042
1043       GNUNET_assert (s != NULL);
1044       if (msg->msg == CURLMSG_DONE)
1045       {
1046         curl_easy_getinfo (easy_h, CURLINFO_RESPONSE_CODE, &http_statuscode);
1047         if (easy_h == s->client_put)
1048         {
1049             if  ((0 != msg->data.result) || (http_statuscode != 200))
1050             {
1051                 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1052                   "Session %p/connection %p: PUT connection to `%s' ended with status %i reason %i: `%s'\n",
1053                   s, msg->easy_handle, GNUNET_i2s (&s->target),
1054                   http_statuscode,
1055                   msg->data.result,
1056                   curl_easy_strerror (msg->data.result));
1057             }
1058             else
1059               GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1060                 "Session %p/connection %p: PUT connection to `%s' ended normal\n",
1061                 s, msg->easy_handle, GNUNET_i2s (&s->target));
1062             if (s->client_get == NULL)
1063             {
1064               /* Disconnect other transmission direction and tell transport */
1065             }
1066             curl_multi_remove_handle (plugin->curl_multi_handle, easy_h);
1067             curl_easy_cleanup (easy_h);
1068             s->client_put = NULL;
1069         }
1070         if (easy_h == s->client_get)
1071         {
1072             if  ((0 != msg->data.result) || (http_statuscode != 200))
1073             {
1074               GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1075                 "Session %p/connection %p: GET connection to `%s' ended with status %i reason %i: `%s'\n",
1076                 s, msg->easy_handle, GNUNET_i2s (&s->target),
1077                 http_statuscode,
1078                 msg->data.result,
1079                 curl_easy_strerror (msg->data.result));
1080
1081             }
1082             else
1083               GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1084                 "Session %p/connection %p: GET connection to `%s' ended normal\n",
1085                 s, msg->easy_handle, GNUNET_i2s (&s->target));
1086             /* Disconnect other transmission direction and tell transport */
1087             client_disconnect (s);
1088         }
1089       }
1090     }
1091   }
1092   while (mret == CURLM_CALL_MULTI_PERFORM);
1093   client_schedule (plugin, GNUNET_NO);
1094 }
1095
1096 static int
1097 client_connect_get (struct Session *s)
1098 {
1099   CURLMcode mret;
1100   /* create get connection */
1101   s->client_get = curl_easy_init ();
1102 #if VERBOSE_CURL
1103   curl_easy_setopt (s->client_get, CURLOPT_VERBOSE, 1L);
1104   curl_easy_setopt (s->client_get, CURLOPT_DEBUGFUNCTION, &client_log);
1105   curl_easy_setopt (s->client_get, CURLOPT_DEBUGDATA, s->client_get);
1106 #endif
1107 #if BUILD_HTTPS
1108   curl_easy_setopt (s->client_get, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
1109   curl_easy_setopt (s->client_get, CURLOPT_SSL_VERIFYPEER, 0);
1110   curl_easy_setopt (s->client_get, CURLOPT_SSL_VERIFYHOST, 0);
1111 #endif
1112   curl_easy_setopt (s->client_get, CURLOPT_URL, s->url);
1113   //curl_easy_setopt (s->client_get, CURLOPT_HEADERFUNCTION, &curl_get_header_cb);
1114   //curl_easy_setopt (s->client_get, CURLOPT_WRITEHEADER, ps);
1115   curl_easy_setopt (s->client_get, CURLOPT_READFUNCTION, client_send_cb);
1116   curl_easy_setopt (s->client_get, CURLOPT_READDATA, s);
1117   curl_easy_setopt (s->client_get, CURLOPT_WRITEFUNCTION, client_receive);
1118   curl_easy_setopt (s->client_get, CURLOPT_WRITEDATA, s);
1119   /* No timeout by default, timeout done with session timeout */
1120   curl_easy_setopt (s->client_get, CURLOPT_TIMEOUT, 0);
1121   curl_easy_setopt (s->client_get, CURLOPT_PRIVATE, s);
1122   curl_easy_setopt (s->client_get, CURLOPT_CONNECTTIMEOUT_MS,
1123                     (long) HTTP_CLIENT_NOT_VALIDATED_TIMEOUT.rel_value);
1124   curl_easy_setopt (s->client_get, CURLOPT_BUFFERSIZE,
1125                     2 * GNUNET_SERVER_MAX_MESSAGE_SIZE);
1126 #if CURL_TCP_NODELAY
1127   curl_easy_setopt (ps->recv_endpoint, CURLOPT_TCP_NODELAY, 1);
1128 #endif
1129   mret = curl_multi_add_handle (s->plugin->curl_multi_handle, s->client_get);
1130   if (mret != CURLM_OK)
1131   {
1132       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, s->plugin->name,
1133                        "Session %p : Failed to add GET handle to multihandle: `%s'\n",
1134                        s, curl_multi_strerror (mret));
1135     curl_easy_cleanup (s->client_get);
1136     s->client_get = NULL;
1137     GNUNET_break (0);
1138     return GNUNET_SYSERR;
1139   }
1140
1141   return GNUNET_OK;
1142 }
1143
1144 static int
1145 client_connect_put (struct Session *s)
1146 {
1147   CURLMcode mret;
1148   /* create put connection */
1149   if (NULL == s->client_put)
1150   {
1151       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, s->plugin->name,
1152                        "Session %p : Init PUT handle \n", s);
1153     s->client_put = curl_easy_init ();
1154   }
1155   else
1156   {
1157       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, s->plugin->name,
1158                        "Session %p : Reusing PUT handle %p \n", s, s->client_put);
1159   }
1160 #if VERBOSE_CURL
1161   curl_easy_setopt (s->client_put, CURLOPT_VERBOSE, 1L);
1162   curl_easy_setopt (s->client_put, CURLOPT_DEBUGFUNCTION, &client_log);
1163   curl_easy_setopt (s->client_put, CURLOPT_DEBUGDATA, s->client_put);
1164 #endif
1165 #if BUILD_HTTPS
1166   curl_easy_setopt (s->client_put, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
1167   curl_easy_setopt (s->client_put, CURLOPT_SSL_VERIFYPEER, 0);
1168   curl_easy_setopt (s->client_put, CURLOPT_SSL_VERIFYHOST, 0);
1169 #endif
1170   curl_easy_setopt (s->client_put, CURLOPT_URL, s->url);
1171   curl_easy_setopt (s->client_put, CURLOPT_UPLOAD, 1L);
1172   //curl_easy_setopt (s->client_put, CURLOPT_HEADERFUNCTION, &client_curl_header);
1173   //curl_easy_setopt (s->client_put, CURLOPT_WRITEHEADER, ps);
1174   curl_easy_setopt (s->client_put, CURLOPT_READFUNCTION, client_send_cb);
1175   curl_easy_setopt (s->client_put, CURLOPT_READDATA, s);
1176   curl_easy_setopt (s->client_put, CURLOPT_WRITEFUNCTION, client_receive_put);
1177   curl_easy_setopt (s->client_put, CURLOPT_WRITEDATA, s);
1178   /* No timeout by default, timeout done with session timeout */
1179   curl_easy_setopt (s->client_put, CURLOPT_TIMEOUT, 0);
1180   curl_easy_setopt (s->client_put, CURLOPT_PRIVATE, s);
1181   curl_easy_setopt (s->client_put, CURLOPT_CONNECTTIMEOUT_MS,
1182                     (long) HTTP_CLIENT_NOT_VALIDATED_TIMEOUT.rel_value);
1183   curl_easy_setopt (s->client_put, CURLOPT_BUFFERSIZE,
1184                     2 * GNUNET_SERVER_MAX_MESSAGE_SIZE);
1185 #if CURL_TCP_NODELAY
1186   curl_easy_setopt (s->client_put, CURLOPT_TCP_NODELAY, 1);
1187 #endif
1188   mret = curl_multi_add_handle (s->plugin->curl_multi_handle, s->client_put);
1189   if (mret != CURLM_OK)
1190   {
1191    GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, s->plugin->name,
1192                     "Session %p : Failed to add PUT handle to multihandle: `%s'\n",
1193                     s, curl_multi_strerror (mret));
1194     curl_easy_cleanup (s->client_put);
1195     s->client_put = NULL;
1196     return GNUNET_SYSERR;
1197   }
1198   return GNUNET_OK;
1199 }
1200
1201 static int
1202 client_connect (struct Session *s)
1203 {
1204
1205   struct HTTP_Client_Plugin *plugin = s->plugin;
1206   int res = GNUNET_OK;
1207
1208
1209   /* create url */
1210   if (NULL == http_common_plugin_address_to_string (NULL, s->addr, s->addrlen))
1211   {
1212     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1213                      "Invalid address peer `%s'\n",
1214                      GNUNET_i2s (&s->target));
1215     return GNUNET_SYSERR;
1216   }
1217
1218   GNUNET_asprintf (&s->url, "%s/%s;%u",
1219       http_common_plugin_address_to_string (plugin, s->addr, s->addrlen),
1220                    GNUNET_h2s_full (&plugin->env->my_identity->hashPubKey),
1221                    plugin->last_tag);
1222
1223   plugin->last_tag++;
1224
1225   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1226                    "Initiating outbound session peer `%s' using address `%s'\n",
1227                    GNUNET_i2s (&s->target), s->url);
1228
1229   if ((GNUNET_SYSERR == client_connect_get (s)) ||
1230       (GNUNET_SYSERR == client_connect_put (s)))
1231   {
1232       GNUNET_break (0);
1233       return GNUNET_SYSERR;
1234   }
1235
1236   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1237                "Session %p: connected with connections GET %p and PUT %p\n",
1238                s, s->client_get, s->client_put);
1239
1240   /* Perform connect */
1241   plugin->cur_connections += 2;
1242   GNUNET_STATISTICS_set (plugin->env->stats,
1243       "# HTTP client connections",
1244       plugin->cur_connections,
1245       GNUNET_NO);
1246
1247   /* Re-schedule since handles have changed */
1248   if (plugin->client_perform_task != GNUNET_SCHEDULER_NO_TASK)
1249   {
1250     GNUNET_SCHEDULER_cancel (plugin->client_perform_task);
1251     plugin->client_perform_task = GNUNET_SCHEDULER_NO_TASK;
1252   }
1253   plugin->client_perform_task = GNUNET_SCHEDULER_add_now (client_run, plugin);
1254   return res;
1255 }
1256
1257
1258 /**
1259  * Creates a new outbound session the transport service will use to send data to the
1260  * peer
1261  *
1262  * @param cls the plugin
1263  * @param address the address
1264  * @return the session or NULL of max connections exceeded
1265  */
1266 static struct Session *
1267 http_client_plugin_get_session (void *cls,
1268                   const struct GNUNET_HELLO_Address *address)
1269 {
1270   struct HTTP_Client_Plugin *plugin = cls;
1271   struct Session * s = NULL;
1272   struct sockaddr *sa;
1273   struct GNUNET_ATS_Information ats;
1274   size_t salen = 0;
1275   int res;
1276
1277   GNUNET_assert (plugin != NULL);
1278   GNUNET_assert (address != NULL);
1279   GNUNET_assert (address->address != NULL);
1280
1281   /* find existing session */
1282   s = client_lookup_session (plugin, address);
1283   if (s != NULL)
1284     return s;
1285
1286   if (plugin->max_connections <= plugin->cur_connections)
1287   {
1288     GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, plugin->name,
1289                      "Maximum number of connections (%u) reached: "
1290                      "cannot connect to peer `%s'\n",
1291                      plugin->max_connections,
1292                      GNUNET_i2s (&address->peer));
1293     return NULL;
1294   }
1295
1296   ats.type = htonl (GNUNET_ATS_NETWORK_TYPE);
1297   ats.value = htonl (GNUNET_ATS_NET_UNSPECIFIED);
1298   sa = http_common_socket_from_address (address->address, address->address_length, &res);
1299
1300   if (GNUNET_SYSERR == res)
1301   {
1302       return NULL;
1303   }
1304   else if (GNUNET_YES == res)
1305   {
1306       GNUNET_assert (NULL != sa);
1307       if (AF_INET == sa->sa_family)
1308       {
1309           salen = sizeof (struct sockaddr_in);
1310       }
1311       else if (AF_INET == sa->sa_family)
1312       {
1313           salen = sizeof (struct sockaddr_in6);
1314       }
1315       ats = plugin->env->get_address_type (plugin->env->cls, sa, salen);
1316       GNUNET_free (sa);
1317   }
1318   else if (GNUNET_NO == res)
1319   {
1320       ats.value = htonl (GNUNET_ATS_COST_WAN);
1321   }
1322
1323   if (GNUNET_ATS_NET_UNSPECIFIED == ntohl(ats.value))
1324   {
1325       GNUNET_break (0);
1326       return NULL;
1327   }
1328
1329   s = GNUNET_malloc (sizeof (struct Session));
1330   memcpy (&s->target, &address->peer, sizeof (struct GNUNET_PeerIdentity));
1331   s->plugin = plugin;
1332   s->addr = GNUNET_malloc (address->address_length);
1333   memcpy (s->addr, address->address, address->address_length);
1334   s->addrlen = address->address_length;
1335   s->ats_address_network_type = ats.value;
1336   s->put_paused = GNUNET_NO;
1337   s->put_tmp_disconnecting = GNUNET_NO;
1338   s->put_tmp_disconnected = GNUNET_NO;
1339   client_start_session_timeout (s);
1340
1341   /* add new session */
1342   GNUNET_CONTAINER_DLL_insert (plugin->head, plugin->tail, s);
1343
1344   /* initiate new connection */
1345   if (GNUNET_SYSERR == client_connect (s))
1346   {
1347     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
1348                      "Cannot connect to peer `%s' address `%s''\n",
1349                      http_common_plugin_address_to_string (NULL, s->addr, s->addrlen),
1350                      GNUNET_i2s (&s->target));
1351     client_delete_session (s);
1352     return NULL;
1353   }
1354   return s;
1355 }
1356
1357
1358 /**
1359  * Setup http_client plugin
1360  *
1361  * @param plugin the plugin handle
1362  * @return GNUNET_OK on success, GNUNET_SYSERR on error
1363  */
1364 static int
1365 client_start (struct HTTP_Client_Plugin *plugin)
1366 {
1367   curl_global_init (CURL_GLOBAL_ALL);
1368   plugin->curl_multi_handle = curl_multi_init ();
1369
1370   if (NULL == plugin->curl_multi_handle)
1371   {
1372     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
1373                      _("Could not initialize curl multi handle, failed to start %s plugin!\n"),
1374                      plugin->name);
1375     return GNUNET_SYSERR;
1376   }
1377   return GNUNET_OK;
1378 }
1379
1380 /**
1381  * Session was idle, so disconnect it
1382  */
1383 static void
1384 client_session_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1385 {
1386   GNUNET_assert (NULL != cls);
1387   struct Session *s = cls;
1388
1389   s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1390   GNUNET_log (TIMEOUT_LOG,
1391               "Session %p was idle for %llu ms, disconnecting\n",
1392               s, (unsigned long long) CLIENT_SESSION_TIMEOUT.rel_value);
1393
1394   /* call session destroy function */
1395   GNUNET_assert (GNUNET_OK == client_disconnect (s));
1396 }
1397
1398
1399 /**
1400  * Start session timeout for session s
1401  *
1402  * @param s the session
1403  */
1404 static void
1405 client_start_session_timeout (struct Session *s)
1406 {
1407
1408  GNUNET_assert (NULL != s);
1409  GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == s->timeout_task);
1410  s->timeout_task =  GNUNET_SCHEDULER_add_delayed (CLIENT_SESSION_TIMEOUT,
1411                                                   &client_session_timeout,
1412                                                   s);
1413  GNUNET_log (TIMEOUT_LOG,
1414              "Timeout for session %p set to %llu ms\n",
1415              s,  (unsigned long long) CLIENT_SESSION_TIMEOUT.rel_value);
1416 }
1417
1418
1419 /**
1420  * Increment session timeout due to activity for session s
1421  *
1422  * param s the session
1423  */
1424 static void
1425 client_reschedule_session_timeout (struct Session *s)
1426 {
1427
1428  GNUNET_assert (NULL != s);
1429  GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != s->timeout_task);
1430
1431  GNUNET_SCHEDULER_cancel (s->timeout_task);
1432  s->timeout_task =  GNUNET_SCHEDULER_add_delayed (CLIENT_SESSION_TIMEOUT,
1433                                                   &client_session_timeout,
1434                                                   s);
1435  GNUNET_log (TIMEOUT_LOG,
1436              "Timeout rescheduled for session %p set to %llu ms\n",
1437              s, (unsigned long long) CLIENT_SESSION_TIMEOUT.rel_value);
1438 }
1439
1440
1441 /**
1442  * Cancel timeout due to activity for session s
1443  *
1444  * param s the session
1445  */
1446 static void
1447 client_stop_session_timeout (struct Session *s)
1448 {
1449  GNUNET_assert (NULL != s);
1450
1451  if (GNUNET_SCHEDULER_NO_TASK != s->timeout_task)
1452  {
1453    GNUNET_SCHEDULER_cancel (s->timeout_task);
1454    s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1455    GNUNET_log (TIMEOUT_LOG, "Timeout stopped for session %p\n", s);
1456  }
1457 }
1458
1459
1460 /**
1461  * Another peer has suggested an address for this
1462  * peer and transport plugin.  Check that this could be a valid
1463  * address.  If so, consider adding it to the list
1464  * of addresses.
1465  *
1466  * @param cls closure
1467  * @param addr pointer to the address
1468  * @param addrlen length of addr
1469  * @return GNUNET_OK if this is a plausible address for this peer
1470  *         and transport
1471  */
1472 static int
1473 http_client_plugin_address_suggested (void *cls, const void *addr, size_t addrlen)
1474 {
1475   /* struct Plugin *plugin = cls; */
1476
1477   /* A HTTP/S client does not have any valid address so:*/
1478   return GNUNET_NO;
1479 }
1480
1481
1482 /**
1483  * Exit point from the plugin.
1484  *
1485  * @param cls api as closure
1486  * @return NULL
1487  */
1488 void *
1489 LIBGNUNET_PLUGIN_TRANSPORT_DONE (void *cls)
1490 {
1491   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1492   struct HTTP_Client_Plugin *plugin = api->cls;
1493   struct Session *pos;
1494   struct Session *next;
1495
1496   if (NULL == api->cls)
1497   {
1498     /* Stub shutdown */
1499     GNUNET_free (api);
1500     return NULL;
1501   }
1502
1503   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1504                    _("Shutting down plugin `%s'\n"),
1505                    plugin->name);
1506
1507
1508   next = plugin->head;
1509   while (NULL != (pos = next))
1510   {
1511       next = pos->next;
1512       client_disconnect (pos);
1513   }
1514   if (GNUNET_SCHEDULER_NO_TASK != plugin->client_perform_task)
1515   {
1516       GNUNET_SCHEDULER_cancel (plugin->client_perform_task);
1517       plugin->client_perform_task = GNUNET_SCHEDULER_NO_TASK;
1518   }
1519
1520
1521   if (NULL != plugin->curl_multi_handle)
1522   {
1523     curl_multi_cleanup (plugin->curl_multi_handle);
1524     plugin->curl_multi_handle = NULL;
1525   }
1526   curl_global_cleanup ();
1527
1528   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1529                    _("Shutdown for plugin `%s' complete\n"),
1530                    plugin->name);
1531
1532   GNUNET_free (plugin);
1533   GNUNET_free (api);
1534   return NULL;
1535 }
1536
1537
1538 /**
1539  * Configure plugin
1540  *
1541  * @param plugin the plugin handle
1542  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
1543  */
1544 static int
1545 client_configure_plugin (struct HTTP_Client_Plugin *plugin)
1546 {
1547   unsigned long long max_connections;
1548
1549   /* Optional parameters */
1550   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (plugin->env->cfg,
1551                       plugin->name,
1552                       "MAX_CONNECTIONS", &max_connections))
1553     max_connections = 128;
1554   plugin->max_connections = max_connections;
1555
1556   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1557                    _("Maximum number of connections is %u\n"),
1558                    plugin->max_connections);
1559   return GNUNET_OK;
1560 }
1561
1562 /**
1563  * Entry point for the plugin.
1564  */
1565 void *
1566 LIBGNUNET_PLUGIN_TRANSPORT_INIT (void *cls)
1567 {
1568   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1569   struct GNUNET_TRANSPORT_PluginFunctions *api;
1570   struct HTTP_Client_Plugin *plugin;
1571
1572   if (NULL == env->receive)
1573   {
1574     /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
1575        initialze the plugin or the API */
1576     api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1577     api->cls = NULL;
1578     api->address_to_string = &http_common_plugin_address_to_string;
1579     api->string_to_address = &http_common_plugin_string_to_address;
1580     api->address_pretty_printer = &http_common_plugin_address_pretty_printer;
1581     return api;
1582   }
1583
1584   plugin = GNUNET_malloc (sizeof (struct HTTP_Client_Plugin));
1585   p = plugin;
1586   plugin->env = env;
1587   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1588   api->cls = plugin;
1589   api->send = &http_client_plugin_send;
1590   api->disconnect = &http_client_plugin_disconnect;
1591   api->check_address = &http_client_plugin_address_suggested;
1592   api->get_session = &http_client_plugin_get_session;
1593   api->address_to_string = &http_common_plugin_address_to_string;
1594   api->string_to_address = &http_common_plugin_string_to_address;
1595   api->address_pretty_printer = &http_common_plugin_address_pretty_printer;
1596
1597
1598 #if BUILD_HTTPS
1599   plugin->name = "transport-https_client";
1600   plugin->protocol = "https";
1601 #else
1602   plugin->name = "transport-http_client";
1603   plugin->protocol = "http";
1604 #endif
1605   plugin->last_tag = 1;
1606
1607   if (GNUNET_SYSERR == client_configure_plugin (plugin))
1608   {
1609       LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
1610       return NULL;
1611   }
1612
1613   /* Start client */
1614   if (GNUNET_SYSERR == client_start (plugin))
1615   {
1616       LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
1617       return NULL;
1618   }
1619   return api;
1620 }
1621
1622 /* end of plugin_transport_http_client.c */