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