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