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_ERROR, s->plugin->name,
453                    "Session %p/connection %p: Sending message with %u to peer `%s' \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_disconnecting)
469   {
470     /* PUT connection is currently getting disconnected */
471     GNUNET_break (0);
472     return msgbuf_size;
473   }
474   else if (GNUNET_YES == s->put_paused)
475   {
476     /* PUT connection was paused, unpause */
477     GNUNET_assert (s->put_disconnect_task != GNUNET_SCHEDULER_NO_TASK);
478     GNUNET_SCHEDULER_cancel (s->put_disconnect_task);
479     s->put_disconnect_task = GNUNET_SCHEDULER_NO_TASK;
480     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, s->plugin->name,
481                      "Session %p/connection %p: unpausing connection\n",
482                      s, s->client_put);
483     s->put_paused = GNUNET_NO;
484     curl_easy_pause (s->client_put, CURLPAUSE_CONT);
485   }
486   else if (GNUNET_YES == s->put_tmp_disconnected)
487   {
488     /* PUT connection was disconnected, reconnect */
489     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, s->plugin->name,
490                      "Session %p: Reconnecting PUT connection\n",
491                      s);
492     s->put_tmp_disconnected = GNUNET_NO;
493     GNUNET_break (s->client_put == NULL);
494     if (GNUNET_SYSERR == client_connect_put (s))
495     {
496       return GNUNET_SYSERR;
497     }
498   }
499
500   client_schedule (s->plugin, GNUNET_YES);
501   client_reschedule_session_timeout (s);
502   return msgbuf_size;
503 }
504
505
506 /**
507  * Delete session s
508  *
509  * @param s the session to delete
510  */
511 static void
512 client_delete_session (struct Session *s)
513 {
514   struct HTTP_Client_Plugin *plugin = s->plugin;
515   struct HTTP_Message *pos;
516   struct HTTP_Message *next;
517
518   client_stop_session_timeout (s);
519
520   if (GNUNET_SCHEDULER_NO_TASK != s->put_disconnect_task)
521   {
522       GNUNET_SCHEDULER_cancel (s->put_disconnect_task);
523       s->put_disconnect_task = GNUNET_SCHEDULER_NO_TASK;
524   }
525
526   GNUNET_CONTAINER_DLL_remove (plugin->head, plugin->tail, s);
527
528   next = s->msg_head;
529   while (NULL != (pos = next))
530   {
531     next = pos->next;
532     GNUNET_CONTAINER_DLL_remove (s->msg_head, s->msg_tail, pos);
533     if (pos->transmit_cont != NULL)
534       pos->transmit_cont (pos->transmit_cont_cls, &s->target, GNUNET_SYSERR);
535     GNUNET_free (pos);
536   }
537
538   if (s->msg_tk != NULL)
539   {
540     GNUNET_SERVER_mst_destroy (s->msg_tk);
541     s->msg_tk = NULL;
542   }
543   GNUNET_free (s->addr);
544   GNUNET_free (s->url);
545   GNUNET_free (s);
546 }
547
548
549
550 /**
551  * Disconnect a session
552  *
553  * @param s session
554  * @return GNUNET_OK on success, GNUNET_SYSERR on error
555  */
556 static int
557 client_disconnect (struct Session *s)
558 {
559   struct HTTP_Client_Plugin *plugin = s->plugin;
560   struct HTTP_Message *msg;
561   struct HTTP_Message *t;
562   int res = GNUNET_OK;
563   CURLMcode mret;
564
565   if (GNUNET_YES != client_exist_session (plugin, s))
566   {
567     GNUNET_break (0);
568     return GNUNET_SYSERR;
569   }
570
571   if (s->client_put != NULL)
572   {
573     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
574                      "Session %p/connection %p: disconnecting PUT connection to peer `%s'\n",
575                      s, s->client_put, GNUNET_i2s (&s->target));
576
577     /* remove curl handle from multi handle */
578     mret = curl_multi_remove_handle (plugin->curl_multi_handle, s->client_put);
579     if (mret != CURLM_OK)
580     {
581       /* clean up easy handle, handle is now invalid and free'd */
582       res = GNUNET_SYSERR;
583       GNUNET_break (0);
584     }
585     curl_easy_cleanup (s->client_put);
586     s->client_put = NULL;
587   }
588
589
590   if (s->recv_wakeup_task != GNUNET_SCHEDULER_NO_TASK)
591   {
592     GNUNET_SCHEDULER_cancel (s->recv_wakeup_task);
593     s->recv_wakeup_task = GNUNET_SCHEDULER_NO_TASK;
594   }
595
596   if (s->client_get != NULL)
597   {
598       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
599                        "Session %p/connection %p: disconnecting GET connection to peer `%s'\n",
600                        s, s->client_get, GNUNET_i2s (&s->target));
601
602     /* remove curl handle from multi handle */
603     mret = curl_multi_remove_handle (plugin->curl_multi_handle, s->client_get);
604     if (mret != CURLM_OK)
605     {
606       /* clean up easy handle, handle is now invalid and free'd */
607       res = GNUNET_SYSERR;
608       GNUNET_break (0);
609     }
610     curl_easy_cleanup (s->client_get);
611     s->client_get = NULL;
612   }
613
614   msg = s->msg_head;
615   while (msg != NULL)
616   {
617     t = msg->next;
618     if (NULL != msg->transmit_cont)
619       msg->transmit_cont (msg->transmit_cont_cls, &s->target, GNUNET_SYSERR);
620     GNUNET_CONTAINER_DLL_remove (s->msg_head, s->msg_tail, msg);
621     GNUNET_free (msg);
622     msg = t;
623   }
624
625   GNUNET_assert (plugin->cur_connections >= 2);
626   plugin->cur_connections -= 2;
627   GNUNET_STATISTICS_set (plugin->env->stats,
628       "# HTTP client sessions",
629       plugin->cur_connections,
630       GNUNET_NO);
631
632   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
633                    "Session %p: notifying transport about ending session\n",s);
634
635   plugin->env->session_end (plugin->env->cls, &s->target, s);
636   client_delete_session (s);
637
638   /* Re-schedule since handles have changed */
639   if (plugin->client_perform_task != GNUNET_SCHEDULER_NO_TASK)
640   {
641     GNUNET_SCHEDULER_cancel (plugin->client_perform_task);
642     plugin->client_perform_task = GNUNET_SCHEDULER_NO_TASK;
643   }
644   client_schedule (plugin, GNUNET_YES);
645
646   return res;
647 }
648
649
650 /**
651  * Function that can be used to force the plugin to disconnect
652  * from the given peer and cancel all previous transmissions
653  * (and their continuationc).
654  *
655  * @param cls closure
656  * @param target peer from which to disconnect
657  */
658 static void
659 http_client_plugin_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
660 {
661   struct HTTP_Client_Plugin *plugin = cls;
662   struct Session *next = NULL;
663   struct Session *pos = NULL;
664
665   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
666                    "Transport tells me to disconnect `%s'\n",
667                    GNUNET_i2s (target));
668
669   next = plugin->head;
670   while (NULL != (pos = next))
671   {
672     next = pos->next;
673     if (0 == memcmp (target, &pos->target, sizeof (struct GNUNET_PeerIdentity)))
674     {
675       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
676                        "Disconnecting session %p to `%pos'\n",
677                        pos, GNUNET_i2s (target));
678       GNUNET_assert (GNUNET_OK == client_disconnect (pos));
679     }
680   }
681
682 }
683
684
685 static struct Session *
686 client_lookup_session (struct HTTP_Client_Plugin *plugin,
687                        const struct GNUNET_HELLO_Address *address)
688 {
689   struct Session *pos;
690
691   for (pos = plugin->head; NULL != pos; pos = pos->next)
692     if ((0 == memcmp (&address->peer, &pos->target, sizeof (struct GNUNET_PeerIdentity))) &&
693         (address->address_length == pos->addrlen) &&
694         (0 == memcmp (address->address, pos->addr, pos->addrlen)))
695       return pos;
696   return NULL;
697 }
698
699 static void
700 client_put_disconnect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
701 {
702   struct Session *s = cls;
703   s->put_disconnect_task = GNUNET_SCHEDULER_NO_TASK;
704   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, s->plugin->name,
705                    "Session %p/connection %p: will be disconnected due to no activity\n",
706                    s, s->client_put);
707   s->put_paused = GNUNET_NO;
708   s->put_tmp_disconnecting = GNUNET_YES;
709   curl_easy_pause (s->client_put, CURLPAUSE_CONT);
710   client_schedule (s->plugin, GNUNET_YES);
711 }
712
713
714
715 /**
716  * Callback method used with libcurl
717  * Method is called when libcurl needs to read data during sending
718  *
719  * @param stream pointer where to write data
720  * @param size size of an individual element
721  * @param nmemb count of elements that can be written to the buffer
722  * @param cls source pointer, passed to the libcurl handle
723  * @return bytes written to stream, returning 0 will terminate connection!
724  */
725 static size_t
726 client_send_cb (void *stream, size_t size, size_t nmemb, void *cls)
727 {
728   struct Session *s = cls;
729   struct HTTP_Client_Plugin *plugin = s->plugin;
730   struct HTTP_Message *msg = s->msg_head;
731   size_t len;
732
733   if (GNUNET_YES != client_exist_session (plugin, s))
734   {
735     GNUNET_break (0);
736     return 0;
737   }
738   if (GNUNET_YES == s->put_tmp_disconnecting)
739   {
740
741       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, s->plugin->name,
742                        "Session %p/connection %p: disconnect due to inactivity\n",
743                        s, s->client_put);
744       return 0;
745   }
746
747   if (NULL == msg)
748   {
749     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
750                      "Session %p/connection %p: nothing to send, suspending\n",
751                      s, s->client_put);
752     s->put_disconnect_task = GNUNET_SCHEDULER_add_delayed (PUT_DISCONNECT_TIMEOUT, &client_put_disconnect, s);
753     s->put_paused = GNUNET_YES;
754     return CURL_READFUNC_PAUSE;
755   }
756   /* data to send */
757   GNUNET_assert (msg->pos < msg->size);
758   /* calculate how much fits in buffer */
759   len = GNUNET_MIN (msg->size - msg->pos,
760                     size * nmemb);
761   memcpy (stream, &msg->buf[msg->pos], len);
762   msg->pos += len;
763   if (msg->pos == msg->size)
764   {
765     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
766                      "Session %p/connection %p: sent message with %u bytes sent, removing message from queue\n",
767                      s, s->client_put, msg->size, msg->pos);
768     /* Calling transmit continuation  */
769     GNUNET_CONTAINER_DLL_remove (s->msg_head, s->msg_tail, msg);
770     if (NULL != msg->transmit_cont)
771       msg->transmit_cont (msg->transmit_cont_cls, &s->target, GNUNET_OK);
772     GNUNET_free (msg);
773   }
774   client_reschedule_session_timeout (s);
775   return len;
776 }
777
778
779 /**
780  * Wake up a curl handle which was suspended
781  *
782  * @param cls the session
783  * @param tc task context
784  */
785 static void
786 client_wake_up (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
787 {
788   struct Session *s = cls;
789
790   if (GNUNET_YES != client_exist_session(p, s))
791   {
792     GNUNET_break (0);
793     return;
794   }
795   s->recv_wakeup_task = GNUNET_SCHEDULER_NO_TASK;
796   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
797     return;
798   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, s->plugin->name,
799                    "Session %p/connection %p: Waking up GET handle\n", s, s->client_get);
800   if (s->client_get != NULL)
801     curl_easy_pause (s->client_get, CURLPAUSE_CONT);
802 }
803
804
805 /**
806  * Callback for message stream tokenizer
807  *
808  * @param cls the session
809  * @param client not used
810  * @param message the message received
811  * @return always GNUNET_OK
812  */
813 static int
814 client_receive_mst_cb (void *cls, void *client,
815                        const struct GNUNET_MessageHeader *message)
816 {
817   struct Session *s = cls;
818   struct HTTP_Client_Plugin *plugin;
819   struct GNUNET_TIME_Relative delay;
820   struct GNUNET_ATS_Information atsi[2];
821   if (GNUNET_YES != client_exist_session(p, s))
822   {
823     GNUNET_break (0);
824     return GNUNET_OK;
825   }
826   plugin = s->plugin;
827
828   atsi[0].type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
829   atsi[0].value = htonl (1);
830   atsi[1].type = htonl (GNUNET_ATS_NETWORK_TYPE);
831   atsi[1].value = s->ats_address_network_type;
832   GNUNET_break (s->ats_address_network_type != ntohl (GNUNET_ATS_NET_UNSPECIFIED));
833
834   delay = s->plugin->env->receive (plugin->env->cls, &s->target, message,
835                                    (const struct GNUNET_ATS_Information *) &atsi, 2,
836                                    s, s->addr, s->addrlen);
837
838   s->next_receive =
839       GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (), delay);
840
841   if (GNUNET_TIME_absolute_get ().abs_value < s->next_receive.abs_value)
842   {
843
844     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
845                      "Client: peer `%s' address `%s' next read delayed for %llu ms\n",
846                      GNUNET_i2s (&s->target), GNUNET_a2s (s->addr, s->addrlen),
847                      delay);
848   }
849   client_reschedule_session_timeout (s);
850   return GNUNET_OK;
851 }
852
853
854 /**
855  * Callback method used with libcurl when data for a PUT connection are
856  * received. We do not expect data here, so we just dismiss it
857  *
858  * @param stream pointer where to write data
859  * @param size size of an individual element
860  * @param nmemb count of elements that can be written to the buffer
861  * @param cls destination pointer, passed to the libcurl handle
862  * @return bytes read from stream
863  */
864 static size_t
865 client_receive_put (void *stream, size_t size, size_t nmemb, void *cls)
866 {
867   return size * nmemb;
868 }
869
870
871 /**
872  * Callback method used with libcurl when data for a GET connection are
873  * received. Forward to MST
874  *
875  * @param stream pointer where to write data
876  * @param size size of an individual element
877  * @param nmemb count of elements that can be written to the buffer
878  * @param cls destination pointer, passed to the libcurl handle
879  * @return bytes read from stream
880  */
881 static size_t
882 client_receive (void *stream, size_t size, size_t nmemb, void *cls)
883 {
884   struct Session *s = cls;
885   struct GNUNET_TIME_Absolute now;
886   size_t len = size * nmemb;
887   struct HTTP_Client_Plugin *plugin = s->plugin;
888
889   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
890                    "Session %p / connection %p: Received %u bytes from peer `%s'\n",
891                    s, s->client_get,
892                    len, GNUNET_i2s (&s->target));
893   now = GNUNET_TIME_absolute_get ();
894   if (now.abs_value < s->next_receive.abs_value)
895   {
896     struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
897     struct GNUNET_TIME_Relative delta =
898         GNUNET_TIME_absolute_get_difference (now, s->next_receive);
899     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
900                      "Session %p / connection %p: No inbound bandwidth available! Next read was delayed for %llu ms\n",
901                      s, s->client_get, delta.rel_value);
902     if (s->recv_wakeup_task != GNUNET_SCHEDULER_NO_TASK)
903     {
904       GNUNET_SCHEDULER_cancel (s->recv_wakeup_task);
905       s->recv_wakeup_task = GNUNET_SCHEDULER_NO_TASK;
906     }
907     s->recv_wakeup_task =
908         GNUNET_SCHEDULER_add_delayed (delta, &client_wake_up, s);
909     return CURL_WRITEFUNC_PAUSE;
910   }
911   if (NULL == s->msg_tk)
912     s->msg_tk = GNUNET_SERVER_mst_create (&client_receive_mst_cb, s);
913   GNUNET_SERVER_mst_receive (s->msg_tk, s, stream, len, GNUNET_NO, GNUNET_NO);
914   return len;
915 }
916
917
918 /**
919  * Task performing curl operations
920  *
921  * @param cls plugin as closure
922  * @param tc gnunet scheduler task context
923  */
924 static void
925 client_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
926
927
928 /**
929  * Function setting up file descriptors and scheduling task to run
930  *
931  * @param  plugin plugin as closure
932  * @param now schedule task in 1ms, regardless of what curl may say
933  * @return GNUNET_SYSERR for hard failure, GNUNET_OK for ok
934  */
935 static int
936 client_schedule (struct HTTP_Client_Plugin *plugin, int now)
937 {
938   fd_set rs;
939   fd_set ws;
940   fd_set es;
941   int max;
942   struct GNUNET_NETWORK_FDSet *grs;
943   struct GNUNET_NETWORK_FDSet *gws;
944   long to;
945   CURLMcode mret;
946   struct GNUNET_TIME_Relative timeout;
947
948   /* Cancel previous scheduled task */
949   if (plugin->client_perform_task != GNUNET_SCHEDULER_NO_TASK)
950   {
951     GNUNET_SCHEDULER_cancel (plugin->client_perform_task);
952     plugin->client_perform_task = GNUNET_SCHEDULER_NO_TASK;
953   }
954   max = -1;
955   FD_ZERO (&rs);
956   FD_ZERO (&ws);
957   FD_ZERO (&es);
958   mret = curl_multi_fdset (plugin->curl_multi_handle, &rs, &ws, &es, &max);
959   if (mret != CURLM_OK)
960   {
961     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("%s failed at %s:%d: `%s'\n"),
962                 "curl_multi_fdset", __FILE__, __LINE__,
963                 curl_multi_strerror (mret));
964     return GNUNET_SYSERR;
965   }
966   mret = curl_multi_timeout (plugin->curl_multi_handle, &to);
967   if (to == -1)
968     timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1);
969   else
970     timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, to);
971   if (now == GNUNET_YES)
972     timeout = GNUNET_TIME_UNIT_MILLISECONDS;
973
974   if (mret != CURLM_OK)
975   {
976     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("%s failed at %s:%d: `%s'\n"),
977                 "curl_multi_timeout", __FILE__, __LINE__,
978                 curl_multi_strerror (mret));
979     return GNUNET_SYSERR;
980   }
981
982   grs = GNUNET_NETWORK_fdset_create ();
983   gws = GNUNET_NETWORK_fdset_create ();
984   GNUNET_NETWORK_fdset_copy_native (grs, &rs, max + 1);
985   GNUNET_NETWORK_fdset_copy_native (gws, &ws, max + 1);
986
987   plugin->client_perform_task =
988       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
989                                    timeout, grs, gws,
990                                    &client_run, plugin);
991   GNUNET_NETWORK_fdset_destroy (gws);
992   GNUNET_NETWORK_fdset_destroy (grs);
993   return GNUNET_OK;
994 }
995
996
997 /**
998  * Task performing curl operations
999  *
1000  * @param cls plugin as closure
1001  * @param tc gnunet scheduler task context
1002  */
1003 static void
1004 client_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1005 {
1006   struct HTTP_Client_Plugin *plugin = cls;
1007   int running;
1008   int http_statuscode;
1009   CURLMcode mret;
1010
1011   GNUNET_assert (cls != NULL);
1012
1013   plugin->client_perform_task = GNUNET_SCHEDULER_NO_TASK;
1014   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1015     return;
1016
1017   do
1018   {
1019     running = 0;
1020     mret = curl_multi_perform (plugin->curl_multi_handle, &running);
1021
1022     CURLMsg *msg;
1023     int msgs_left;
1024
1025     while ((msg = curl_multi_info_read (plugin->curl_multi_handle, &msgs_left)))
1026     {
1027       CURL *easy_h = msg->easy_handle;
1028       struct Session *s = NULL;
1029       char *d = (char *) s;
1030
1031       if (easy_h == NULL)
1032       {
1033         GNUNET_break (0);
1034         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1035                          "Client: connection to ended with reason %i: `%s', %i handles running\n",
1036                          msg->data.result,
1037                          curl_easy_strerror (msg->data.result), running);
1038         continue;
1039       }
1040
1041       GNUNET_assert (CURLE_OK ==
1042                      curl_easy_getinfo (easy_h, CURLINFO_PRIVATE, &d));
1043       s = (struct Session *) d;
1044
1045       if (GNUNET_YES != client_exist_session(plugin, s))
1046       {
1047         GNUNET_break (0);
1048         return;
1049       }
1050
1051       GNUNET_assert (s != NULL);
1052       if (msg->msg == CURLMSG_DONE)
1053       {
1054         curl_easy_getinfo (easy_h, CURLINFO_RESPONSE_CODE, &http_statuscode);
1055         if (easy_h == s->client_put)
1056         {
1057             if  ((0 != msg->data.result) || (http_statuscode != 200))
1058             {
1059                 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
1060                   "Session %p/connection %p: PUT connection to `%s' ended with status %i reason %i: `%s'\n",
1061                   s, msg->easy_handle, GNUNET_i2s (&s->target),
1062                   http_statuscode,
1063                   msg->data.result,
1064                   curl_easy_strerror (msg->data.result));
1065             }
1066             else
1067               GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
1068                 "Session %p/connection %p: PUT connection to `%s' ended normal\n",
1069                 s, msg->easy_handle, GNUNET_i2s (&s->target));
1070             if (s->client_get == NULL)
1071             {
1072               /* Disconnect other transmission direction and tell transport */
1073             }
1074             curl_multi_remove_handle (plugin->curl_multi_handle, easy_h);
1075             curl_easy_cleanup (easy_h);
1076             s->put_tmp_disconnecting = GNUNET_NO;
1077             s->put_tmp_disconnected = GNUNET_YES;
1078             s->client_put = NULL;
1079         }
1080         if (easy_h == s->client_get)
1081         {
1082             if  ((0 != msg->data.result) || (http_statuscode != 200))
1083             {
1084               GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1085                 "Session %p/connection %p: GET connection to `%s' ended with status %i reason %i: `%s'\n",
1086                 s, msg->easy_handle, GNUNET_i2s (&s->target),
1087                 http_statuscode,
1088                 msg->data.result,
1089                 curl_easy_strerror (msg->data.result));
1090
1091             }
1092             else
1093               GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1094                 "Session %p/connection %p: GET connection to `%s' ended normal\n",
1095                 s, msg->easy_handle, GNUNET_i2s (&s->target));
1096             /* Disconnect other transmission direction and tell transport */
1097             client_disconnect (s);
1098         }
1099       }
1100     }
1101   }
1102   while (mret == CURLM_CALL_MULTI_PERFORM);
1103   client_schedule (plugin, GNUNET_NO);
1104 }
1105
1106 static int
1107 client_connect_get (struct Session *s)
1108 {
1109   CURLMcode mret;
1110   /* create get connection */
1111   s->client_get = curl_easy_init ();
1112 #if VERBOSE_CURL
1113   curl_easy_setopt (s->client_get, CURLOPT_VERBOSE, 1L);
1114   curl_easy_setopt (s->client_get, CURLOPT_DEBUGFUNCTION, &client_log);
1115   curl_easy_setopt (s->client_get, CURLOPT_DEBUGDATA, s->client_get);
1116 #endif
1117 #if BUILD_HTTPS
1118   curl_easy_setopt (s->client_get, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
1119   curl_easy_setopt (s->client_get, CURLOPT_SSL_VERIFYPEER, 0);
1120   curl_easy_setopt (s->client_get, CURLOPT_SSL_VERIFYHOST, 0);
1121 #endif
1122   curl_easy_setopt (s->client_get, CURLOPT_URL, s->url);
1123   //curl_easy_setopt (s->client_get, CURLOPT_HEADERFUNCTION, &curl_get_header_cb);
1124   //curl_easy_setopt (s->client_get, CURLOPT_WRITEHEADER, ps);
1125   curl_easy_setopt (s->client_get, CURLOPT_READFUNCTION, client_send_cb);
1126   curl_easy_setopt (s->client_get, CURLOPT_READDATA, s);
1127   curl_easy_setopt (s->client_get, CURLOPT_WRITEFUNCTION, client_receive);
1128   curl_easy_setopt (s->client_get, CURLOPT_WRITEDATA, s);
1129   /* No timeout by default, timeout done with session timeout */
1130   curl_easy_setopt (s->client_get, CURLOPT_TIMEOUT, 0);
1131   curl_easy_setopt (s->client_get, CURLOPT_PRIVATE, s);
1132   curl_easy_setopt (s->client_get, CURLOPT_CONNECTTIMEOUT_MS,
1133                     (long) HTTP_CLIENT_NOT_VALIDATED_TIMEOUT.rel_value);
1134   curl_easy_setopt (s->client_get, CURLOPT_BUFFERSIZE,
1135                     2 * GNUNET_SERVER_MAX_MESSAGE_SIZE);
1136 #if CURL_TCP_NODELAY
1137   curl_easy_setopt (ps->recv_endpoint, CURLOPT_TCP_NODELAY, 1);
1138 #endif
1139   mret = curl_multi_add_handle (s->plugin->curl_multi_handle, s->client_get);
1140   if (mret != CURLM_OK)
1141   {
1142       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, s->plugin->name,
1143                        "Session %p : Failed to add GET handle to multihandle: `%s'\n",
1144                        s, curl_multi_strerror (mret));
1145     curl_easy_cleanup (s->client_get);
1146     s->client_get = NULL;
1147     GNUNET_break (0);
1148     return GNUNET_SYSERR;
1149   }
1150
1151   return GNUNET_OK;
1152 }
1153
1154 static int
1155 client_connect_put (struct Session *s)
1156 {
1157   CURLMcode mret;
1158   /* create put connection */
1159   GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, s->plugin->name,
1160                        "Session %p : Init PUT handle \n", s);
1161   s->client_put = curl_easy_init ();
1162 #if VERBOSE_CURL
1163   curl_easy_setopt (s->client_put, CURLOPT_VERBOSE, 1L);
1164   curl_easy_setopt (s->client_put, CURLOPT_DEBUGFUNCTION, &client_log);
1165   curl_easy_setopt (s->client_put, CURLOPT_DEBUGDATA, s->client_put);
1166 #endif
1167 #if BUILD_HTTPS
1168   curl_easy_setopt (s->client_put, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
1169   curl_easy_setopt (s->client_put, CURLOPT_SSL_VERIFYPEER, 0);
1170   curl_easy_setopt (s->client_put, CURLOPT_SSL_VERIFYHOST, 0);
1171 #endif
1172   curl_easy_setopt (s->client_put, CURLOPT_URL, s->url);
1173   curl_easy_setopt (s->client_put, CURLOPT_UPLOAD, 1L);
1174   //curl_easy_setopt (s->client_put, CURLOPT_HEADERFUNCTION, &client_curl_header);
1175   //curl_easy_setopt (s->client_put, CURLOPT_WRITEHEADER, ps);
1176   curl_easy_setopt (s->client_put, CURLOPT_READFUNCTION, client_send_cb);
1177   curl_easy_setopt (s->client_put, CURLOPT_READDATA, s);
1178   curl_easy_setopt (s->client_put, CURLOPT_WRITEFUNCTION, client_receive_put);
1179   curl_easy_setopt (s->client_put, CURLOPT_WRITEDATA, s);
1180   /* No timeout by default, timeout done with session timeout */
1181   curl_easy_setopt (s->client_put, CURLOPT_TIMEOUT, 0);
1182   curl_easy_setopt (s->client_put, CURLOPT_PRIVATE, s);
1183   curl_easy_setopt (s->client_put, CURLOPT_CONNECTTIMEOUT_MS,
1184                     (long) HTTP_CLIENT_NOT_VALIDATED_TIMEOUT.rel_value);
1185   curl_easy_setopt (s->client_put, CURLOPT_BUFFERSIZE,
1186                     2 * GNUNET_SERVER_MAX_MESSAGE_SIZE);
1187 #if CURL_TCP_NODELAY
1188   curl_easy_setopt (s->client_put, CURLOPT_TCP_NODELAY, 1);
1189 #endif
1190   mret = curl_multi_add_handle (s->plugin->curl_multi_handle, s->client_put);
1191   if (mret != CURLM_OK)
1192   {
1193    GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, s->plugin->name,
1194                     "Session %p : Failed to add PUT handle to multihandle: `%s'\n",
1195                     s, curl_multi_strerror (mret));
1196     curl_easy_cleanup (s->client_put);
1197     s->client_put = NULL;
1198     return GNUNET_SYSERR;
1199   }
1200   return GNUNET_OK;
1201 }
1202
1203 static int
1204 client_connect (struct Session *s)
1205 {
1206
1207   struct HTTP_Client_Plugin *plugin = s->plugin;
1208   int res = GNUNET_OK;
1209
1210
1211   /* create url */
1212   if (NULL == http_common_plugin_address_to_string (NULL, s->addr, s->addrlen))
1213   {
1214     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1215                      "Invalid address peer `%s'\n",
1216                      GNUNET_i2s (&s->target));
1217     return GNUNET_SYSERR;
1218   }
1219
1220   GNUNET_asprintf (&s->url, "%s/%s;%u",
1221       http_common_plugin_address_to_string (plugin, s->addr, s->addrlen),
1222                    GNUNET_h2s_full (&plugin->env->my_identity->hashPubKey),
1223                    plugin->last_tag);
1224
1225   plugin->last_tag++;
1226
1227   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1228                    "Initiating outbound session peer `%s' using address `%s'\n",
1229                    GNUNET_i2s (&s->target), s->url);
1230
1231   if ((GNUNET_SYSERR == client_connect_get (s)) ||
1232       (GNUNET_SYSERR == client_connect_put (s)))
1233   {
1234       GNUNET_break (0);
1235       return GNUNET_SYSERR;
1236   }
1237
1238   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1239                "Session %p: connected with connections GET %p and PUT %p\n",
1240                s, s->client_get, s->client_put);
1241
1242   /* Perform connect */
1243   plugin->cur_connections += 2;
1244   GNUNET_STATISTICS_set (plugin->env->stats,
1245       "# HTTP client connections",
1246       plugin->cur_connections,
1247       GNUNET_NO);
1248
1249   /* Re-schedule since handles have changed */
1250   if (plugin->client_perform_task != GNUNET_SCHEDULER_NO_TASK)
1251   {
1252     GNUNET_SCHEDULER_cancel (plugin->client_perform_task);
1253     plugin->client_perform_task = GNUNET_SCHEDULER_NO_TASK;
1254   }
1255   plugin->client_perform_task = GNUNET_SCHEDULER_add_now (client_run, plugin);
1256   return res;
1257 }
1258
1259
1260 /**
1261  * Creates a new outbound session the transport service will use to send data to the
1262  * peer
1263  *
1264  * @param cls the plugin
1265  * @param address the address
1266  * @return the session or NULL of max connections exceeded
1267  */
1268 static struct Session *
1269 http_client_plugin_get_session (void *cls,
1270                   const struct GNUNET_HELLO_Address *address)
1271 {
1272   struct HTTP_Client_Plugin *plugin = cls;
1273   struct Session * s = NULL;
1274   struct sockaddr *sa;
1275   struct GNUNET_ATS_Information ats;
1276   size_t salen = 0;
1277   int res;
1278
1279   GNUNET_assert (plugin != NULL);
1280   GNUNET_assert (address != NULL);
1281   GNUNET_assert (address->address != NULL);
1282
1283   /* find existing session */
1284   s = client_lookup_session (plugin, address);
1285   if (s != NULL)
1286     return s;
1287
1288   if (plugin->max_connections <= plugin->cur_connections)
1289   {
1290     GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, plugin->name,
1291                      "Maximum number of connections (%u) reached: "
1292                      "cannot connect to peer `%s'\n",
1293                      plugin->max_connections,
1294                      GNUNET_i2s (&address->peer));
1295     return NULL;
1296   }
1297
1298   ats.type = htonl (GNUNET_ATS_NETWORK_TYPE);
1299   ats.value = htonl (GNUNET_ATS_NET_UNSPECIFIED);
1300   sa = http_common_socket_from_address (address->address, address->address_length, &res);
1301
1302   if (GNUNET_SYSERR == res)
1303   {
1304       return NULL;
1305   }
1306   else if (GNUNET_YES == res)
1307   {
1308       GNUNET_assert (NULL != sa);
1309       if (AF_INET == sa->sa_family)
1310       {
1311           salen = sizeof (struct sockaddr_in);
1312       }
1313       else if (AF_INET == sa->sa_family)
1314       {
1315           salen = sizeof (struct sockaddr_in6);
1316       }
1317       ats = plugin->env->get_address_type (plugin->env->cls, sa, salen);
1318       GNUNET_free (sa);
1319   }
1320   else if (GNUNET_NO == res)
1321   {
1322       ats.value = htonl (GNUNET_ATS_COST_WAN);
1323   }
1324
1325   if (GNUNET_ATS_NET_UNSPECIFIED == ntohl(ats.value))
1326   {
1327       GNUNET_break (0);
1328       return NULL;
1329   }
1330
1331   s = GNUNET_malloc (sizeof (struct Session));
1332   memcpy (&s->target, &address->peer, sizeof (struct GNUNET_PeerIdentity));
1333   s->plugin = plugin;
1334   s->addr = GNUNET_malloc (address->address_length);
1335   memcpy (s->addr, address->address, address->address_length);
1336   s->addrlen = address->address_length;
1337   s->ats_address_network_type = ats.value;
1338   s->put_paused = GNUNET_NO;
1339   s->put_tmp_disconnecting = GNUNET_NO;
1340   s->put_tmp_disconnected = GNUNET_NO;
1341   client_start_session_timeout (s);
1342
1343   /* add new session */
1344   GNUNET_CONTAINER_DLL_insert (plugin->head, plugin->tail, s);
1345
1346   /* initiate new connection */
1347   if (GNUNET_SYSERR == client_connect (s))
1348   {
1349     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
1350                      "Cannot connect to peer `%s' address `%s''\n",
1351                      http_common_plugin_address_to_string (NULL, s->addr, s->addrlen),
1352                      GNUNET_i2s (&s->target));
1353     client_delete_session (s);
1354     return NULL;
1355   }
1356   return s;
1357 }
1358
1359
1360 /**
1361  * Setup http_client plugin
1362  *
1363  * @param plugin the plugin handle
1364  * @return GNUNET_OK on success, GNUNET_SYSERR on error
1365  */
1366 static int
1367 client_start (struct HTTP_Client_Plugin *plugin)
1368 {
1369   curl_global_init (CURL_GLOBAL_ALL);
1370   plugin->curl_multi_handle = curl_multi_init ();
1371
1372   if (NULL == plugin->curl_multi_handle)
1373   {
1374     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
1375                      _("Could not initialize curl multi handle, failed to start %s plugin!\n"),
1376                      plugin->name);
1377     return GNUNET_SYSERR;
1378   }
1379   return GNUNET_OK;
1380 }
1381
1382 /**
1383  * Session was idle, so disconnect it
1384  */
1385 static void
1386 client_session_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1387 {
1388   GNUNET_assert (NULL != cls);
1389   struct Session *s = cls;
1390
1391   s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1392   GNUNET_log (TIMEOUT_LOG,
1393               "Session %p was idle for %llu ms, disconnecting\n",
1394               s, (unsigned long long) CLIENT_SESSION_TIMEOUT.rel_value);
1395
1396   /* call session destroy function */
1397   GNUNET_assert (GNUNET_OK == client_disconnect (s));
1398 }
1399
1400
1401 /**
1402  * Start session timeout for session s
1403  *
1404  * @param s the session
1405  */
1406 static void
1407 client_start_session_timeout (struct Session *s)
1408 {
1409
1410  GNUNET_assert (NULL != s);
1411  GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == s->timeout_task);
1412  s->timeout_task =  GNUNET_SCHEDULER_add_delayed (CLIENT_SESSION_TIMEOUT,
1413                                                   &client_session_timeout,
1414                                                   s);
1415  GNUNET_log (TIMEOUT_LOG,
1416              "Timeout for session %p set to %llu ms\n",
1417              s,  (unsigned long long) CLIENT_SESSION_TIMEOUT.rel_value);
1418 }
1419
1420
1421 /**
1422  * Increment session timeout due to activity for session s
1423  *
1424  * param s the session
1425  */
1426 static void
1427 client_reschedule_session_timeout (struct Session *s)
1428 {
1429
1430  GNUNET_assert (NULL != s);
1431  GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != s->timeout_task);
1432
1433  GNUNET_SCHEDULER_cancel (s->timeout_task);
1434  s->timeout_task =  GNUNET_SCHEDULER_add_delayed (CLIENT_SESSION_TIMEOUT,
1435                                                   &client_session_timeout,
1436                                                   s);
1437  GNUNET_log (TIMEOUT_LOG,
1438              "Timeout rescheduled for session %p set to %llu ms\n",
1439              s, (unsigned long long) CLIENT_SESSION_TIMEOUT.rel_value);
1440 }
1441
1442
1443 /**
1444  * Cancel timeout due to activity for session s
1445  *
1446  * param s the session
1447  */
1448 static void
1449 client_stop_session_timeout (struct Session *s)
1450 {
1451  GNUNET_assert (NULL != s);
1452
1453  if (GNUNET_SCHEDULER_NO_TASK != s->timeout_task)
1454  {
1455    GNUNET_SCHEDULER_cancel (s->timeout_task);
1456    s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1457    GNUNET_log (TIMEOUT_LOG, "Timeout stopped for session %p\n", s);
1458  }
1459 }
1460
1461
1462 /**
1463  * Another peer has suggested an address for this
1464  * peer and transport plugin.  Check that this could be a valid
1465  * address.  If so, consider adding it to the list
1466  * of addresses.
1467  *
1468  * @param cls closure
1469  * @param addr pointer to the address
1470  * @param addrlen length of addr
1471  * @return GNUNET_OK if this is a plausible address for this peer
1472  *         and transport
1473  */
1474 static int
1475 http_client_plugin_address_suggested (void *cls, const void *addr, size_t addrlen)
1476 {
1477   /* struct Plugin *plugin = cls; */
1478
1479   /* A HTTP/S client does not have any valid address so:*/
1480   return GNUNET_NO;
1481 }
1482
1483
1484 /**
1485  * Exit point from the plugin.
1486  *
1487  * @param cls api as closure
1488  * @return NULL
1489  */
1490 void *
1491 LIBGNUNET_PLUGIN_TRANSPORT_DONE (void *cls)
1492 {
1493   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1494   struct HTTP_Client_Plugin *plugin = api->cls;
1495   struct Session *pos;
1496   struct Session *next;
1497
1498   if (NULL == api->cls)
1499   {
1500     /* Stub shutdown */
1501     GNUNET_free (api);
1502     return NULL;
1503   }
1504
1505   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1506                    _("Shutting down plugin `%s'\n"),
1507                    plugin->name);
1508
1509
1510   next = plugin->head;
1511   while (NULL != (pos = next))
1512   {
1513       next = pos->next;
1514       client_disconnect (pos);
1515   }
1516   if (GNUNET_SCHEDULER_NO_TASK != plugin->client_perform_task)
1517   {
1518       GNUNET_SCHEDULER_cancel (plugin->client_perform_task);
1519       plugin->client_perform_task = GNUNET_SCHEDULER_NO_TASK;
1520   }
1521
1522
1523   if (NULL != plugin->curl_multi_handle)
1524   {
1525     curl_multi_cleanup (plugin->curl_multi_handle);
1526     plugin->curl_multi_handle = NULL;
1527   }
1528   curl_global_cleanup ();
1529
1530   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1531                    _("Shutdown for plugin `%s' complete\n"),
1532                    plugin->name);
1533
1534   GNUNET_free (plugin);
1535   GNUNET_free (api);
1536   return NULL;
1537 }
1538
1539
1540 /**
1541  * Configure plugin
1542  *
1543  * @param plugin the plugin handle
1544  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
1545  */
1546 static int
1547 client_configure_plugin (struct HTTP_Client_Plugin *plugin)
1548 {
1549   unsigned long long max_connections;
1550
1551   /* Optional parameters */
1552   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (plugin->env->cfg,
1553                       plugin->name,
1554                       "MAX_CONNECTIONS", &max_connections))
1555     max_connections = 128;
1556   plugin->max_connections = max_connections;
1557
1558   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1559                    _("Maximum number of connections is %u\n"),
1560                    plugin->max_connections);
1561   return GNUNET_OK;
1562 }
1563
1564 /**
1565  * Entry point for the plugin.
1566  */
1567 void *
1568 LIBGNUNET_PLUGIN_TRANSPORT_INIT (void *cls)
1569 {
1570   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1571   struct GNUNET_TRANSPORT_PluginFunctions *api;
1572   struct HTTP_Client_Plugin *plugin;
1573
1574   if (NULL == env->receive)
1575   {
1576     /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
1577        initialze the plugin or the API */
1578     api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1579     api->cls = NULL;
1580     api->address_to_string = &http_common_plugin_address_to_string;
1581     api->string_to_address = &http_common_plugin_string_to_address;
1582     api->address_pretty_printer = &http_common_plugin_address_pretty_printer;
1583     return api;
1584   }
1585
1586   plugin = GNUNET_malloc (sizeof (struct HTTP_Client_Plugin));
1587   p = plugin;
1588   plugin->env = env;
1589   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1590   api->cls = plugin;
1591   api->send = &http_client_plugin_send;
1592   api->disconnect = &http_client_plugin_disconnect;
1593   api->check_address = &http_client_plugin_address_suggested;
1594   api->get_session = &http_client_plugin_get_session;
1595   api->address_to_string = &http_common_plugin_address_to_string;
1596   api->string_to_address = &http_common_plugin_string_to_address;
1597   api->address_pretty_printer = &http_common_plugin_address_pretty_printer;
1598
1599
1600 #if BUILD_HTTPS
1601   plugin->name = "transport-https_client";
1602   plugin->protocol = "https";
1603 #else
1604   plugin->name = "transport-http_client";
1605   plugin->protocol = "http";
1606 #endif
1607   plugin->last_tag = 1;
1608
1609   if (GNUNET_SYSERR == client_configure_plugin (plugin))
1610   {
1611       LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
1612       return NULL;
1613   }
1614
1615   /* Start client */
1616   if (GNUNET_SYSERR == client_start (plugin))
1617   {
1618       LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
1619       return NULL;
1620   }
1621   return api;
1622 }
1623
1624 /* end of plugin_transport_http_client.c */