rename GNUNET_GETOPT functions to achieve better consistency
[oweals/gnunet.git] / src / transport / plugin_transport_http_client.c
1 /*
2      This file is part of GNUnet
3      Copyright (C) 2002-2014 GNUnet e.V.
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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20
21 /**
22  * @file transport/plugin_transport_http_client.c
23  * @brief HTTP/S client transport plugin
24  * @author Matthias Wachs
25  * @author Christian Grothoff
26  */
27
28 #if BUILD_HTTPS
29 #define PLUGIN_NAME "https_client"
30 #define HTTP_STAT_STR_CONNECTIONS "# HTTPS client connections"
31 #define LIBGNUNET_PLUGIN_TRANSPORT_INIT libgnunet_plugin_transport_https_client_init
32 #define LIBGNUNET_PLUGIN_TRANSPORT_DONE libgnunet_plugin_transport_https_client_done
33 #else
34 #define PLUGIN_NAME "http_client"
35 #define HTTP_STAT_STR_CONNECTIONS "# HTTP client connections"
36 #define LIBGNUNET_PLUGIN_TRANSPORT_INIT libgnunet_plugin_transport_http_client_init
37 #define LIBGNUNET_PLUGIN_TRANSPORT_DONE libgnunet_plugin_transport_http_client_done
38 #endif
39
40 #define VERBOSE_CURL GNUNET_NO
41
42 #define PUT_DISCONNECT_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
43
44 #define ENABLE_PUT GNUNET_YES
45 #define ENABLE_GET GNUNET_YES
46
47 #include "platform.h"
48 #include "gnunet_util_lib.h"
49 #include "gnunet_protocols.h"
50 #include "gnunet_transport_plugin.h"
51 #include "plugin_transport_http_common.h"
52 #if HAVE_CURL_CURL_H
53 #include <curl/curl.h>
54 #elif HAVE_GNURL_CURL_H
55 #include <gnurl/curl.h>
56 #endif
57
58
59 #define LOG(kind,...) GNUNET_log_from(kind, PLUGIN_NAME, __VA_ARGS__)
60
61 /**
62  * Encapsulation of all of the state of the plugin.
63  */
64 struct HTTP_Client_Plugin;
65
66 /**
67  * State of a HTTP PUT request
68  */
69 enum HTTP_PUT_REQUEST_STATE
70 {
71   /**
72    *  Just created, not yet connected
73    */
74   H_NOT_CONNECTED,
75
76   /**
77    *  Connected
78    */
79   H_CONNECTED,
80
81   /**
82    *  Paused, nothing to send
83    */
84   H_PAUSED,
85
86   /**
87    * Temporary disconnect in progress due to inactivity
88    */
89   H_TMP_DISCONNECTING,
90
91   /**
92    * Send request while temporary disconnect, reconnect
93    */
94   H_TMP_RECONNECT_REQUIRED,
95
96   /**
97    * Temporarily disconnected
98    */
99   H_TMP_DISCONNECTED,
100
101   /**
102    * Disconnected
103    */
104   H_DISCONNECTED
105 };
106
107 /**
108  *  Message to send using http
109  */
110 struct HTTP_Message
111 {
112   /**
113    * next pointer for double linked list
114    */
115   struct HTTP_Message *next;
116
117   /**
118    * previous pointer for double linked list
119    */
120   struct HTTP_Message *prev;
121
122   /**
123    * buffer containing data to send
124    */
125   char *buf;
126
127   /**
128    * Continuation function to call once the transmission buffer
129    * has again space available.  NULL if there is no
130    * continuation to call.
131    */
132   GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
133
134   /**
135    * Closure for @e transmit_cont.
136    */
137   void *transmit_cont_cls;
138
139   /**
140    * amount of data already sent
141    */
142   size_t pos;
143
144   /**
145    * buffer length
146    */
147   size_t size;
148
149 };
150
151
152 /**
153  * Session handle for HTTP(S) connections.
154  */
155 struct GNUNET_ATS_Session;
156
157
158 /**
159  * A request handle
160  *
161  */
162 struct RequestHandle
163 {
164   /**
165    * Current state of this request
166    */
167   enum HTTP_PUT_REQUEST_STATE state;
168
169   /**
170    * The curl easy handle
171    */
172   CURL *easyhandle;
173
174   /**
175    * The related session
176    */
177   struct GNUNET_ATS_Session *s;
178 };
179
180
181 /**
182  * Session handle for connections.
183  */
184 struct GNUNET_ATS_Session
185 {
186   /**
187    * The URL to connect to
188    */
189   char *url;
190
191   /**
192    * Address
193    */
194   struct GNUNET_HELLO_Address *address;
195
196   /**
197    * Pointer to the global plugin struct.
198    */
199   struct HTTP_Client_Plugin *plugin;
200
201   /**
202    * Handle for the HTTP PUT request.
203    */
204   struct RequestHandle put;
205
206   /**
207    * Handle for the HTTP GET request.
208    */
209   struct RequestHandle get;
210
211   /**
212    * next pointer for double linked list
213    */
214   struct HTTP_Message *msg_head;
215
216   /**
217    * previous pointer for double linked list
218    */
219   struct HTTP_Message *msg_tail;
220
221   /**
222    * Message stream tokenizer for incoming data
223    */
224   struct GNUNET_MessageStreamTokenizer *msg_tk;
225
226   /**
227    * Session timeout task
228    */
229   struct GNUNET_SCHEDULER_Task *put_disconnect_task;
230
231   /**
232    * Session timeout task
233    */
234   struct GNUNET_SCHEDULER_Task *timeout_task;
235
236   /**
237    * Task to wake up client receive handle when receiving is allowed again
238    */
239   struct GNUNET_SCHEDULER_Task *recv_wakeup_task;
240
241   /**
242    * Absolute time when to receive data again.
243    * Used for receive throttling.
244    */
245   struct GNUNET_TIME_Absolute next_receive;
246
247   /**
248    * When does this session time out.
249    */
250   struct GNUNET_TIME_Absolute timeout;
251
252   /**
253    * Number of bytes waiting for transmission to this peer.
254    */
255   unsigned long long bytes_in_queue;
256
257   /**
258    * Outbound overhead due to HTTP connection
259    * Add to next message of this session when calling callback
260    */
261   size_t overhead;
262
263   /**
264    * Number of messages waiting for transmission to this peer.
265    */
266   unsigned int msgs_in_queue;
267
268   /**
269    * ATS network type.
270    */
271   enum GNUNET_ATS_Network_Type scope;
272 };
273
274
275 /**
276  * Encapsulation of all of the state of the plugin.
277  */
278 struct HTTP_Client_Plugin
279 {
280   /**
281    * Our environment.
282    */
283   struct GNUNET_TRANSPORT_PluginEnvironment *env;
284
285   /**
286    * Open sessions.
287    */
288   struct GNUNET_CONTAINER_MultiPeerMap *sessions;
289
290   /**
291    * Function to call about session status changes.
292    */
293   GNUNET_TRANSPORT_SessionInfoCallback sic;
294
295   /**
296    * Closure for @e sic.
297    */
298   void *sic_cls;
299
300   /**
301    * Plugin name
302    */
303   char *name;
304
305   /**
306    * Protocol
307    */
308   char *protocol;
309
310   /**
311    * Proxy configuration: hostname or ip of the proxy server
312    */
313   char *proxy_hostname;
314
315   /**
316    * Username for the proxy server
317    */
318   char *proxy_username;
319
320   /**
321    * Password for the proxy server
322    */
323   char *proxy_password;
324
325   /**
326    * cURL Multihandle
327    */
328   CURLM *curl_multi_handle;
329
330   /**
331    * curl perform task
332    */
333   struct GNUNET_SCHEDULER_Task * client_perform_task;
334
335   /**
336    * Type of proxy server:
337    *
338    * Valid values as supported by curl:
339    * CURLPROXY_HTTP, CURLPROXY_HTTP_1_0 CURLPROXY_SOCKS4, CURLPROXY_SOCKS5,
340    * CURLPROXY_SOCKS4A, CURLPROXY_SOCKS5_HOSTNAME
341    */
342   curl_proxytype proxytype;
343
344   /**
345    * Use proxy tunneling:
346    * Tunnel all operations through a given HTTP instead of have the proxy
347    * evaluate the HTTP request
348    *
349    * Default: #GNUNET_NO, #GNUNET_YES experimental
350    */
351   int proxy_use_httpproxytunnel;
352
353   /**
354    * My options to be included in the address
355    */
356   uint32_t options;
357
358   /**
359    * Maximum number of sockets the plugin can use
360    * Each http connections are two requests
361    */
362   unsigned int max_requests;
363
364   /**
365    * Current number of sockets the plugin can use
366    * Each http connections are two requests
367    */
368   unsigned int cur_requests;
369
370   /**
371    * Last used unique HTTP connection tag
372    */
373   uint32_t last_tag;
374
375   /**
376    * use IPv6
377    */
378   uint16_t use_ipv6;
379
380   /**
381    * use IPv4
382    */
383   uint16_t use_ipv4;
384
385   /**
386    * Should we emulate an XHR client for testing?
387    */
388   int emulate_xhr;
389 };
390
391
392 /**
393  * Disconnect a session
394  *
395  * @param cls the `struct HTTP_Client_Plugin *`
396  * @param s session
397  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
398  */
399 static int
400 http_client_plugin_session_disconnect (void *cls, struct GNUNET_ATS_Session *s);
401
402
403 /**
404  * If a session monitor is attached, notify it about the new
405  * session state.
406  *
407  * @param plugin our plugin
408  * @param session session that changed state
409  * @param state new state of the session
410  */
411 static void
412 notify_session_monitor (struct HTTP_Client_Plugin *plugin,
413                         struct GNUNET_ATS_Session *session,
414                         enum GNUNET_TRANSPORT_SessionState state)
415 {
416   struct GNUNET_TRANSPORT_SessionInfo info;
417
418   if (NULL == plugin->sic)
419     return;
420   memset (&info, 0, sizeof (info));
421   info.state = state;
422   info.is_inbound = GNUNET_NO;
423   info.num_msg_pending = session->msgs_in_queue;
424   info.num_bytes_pending = session->bytes_in_queue;
425   info.receive_delay = session->next_receive;
426   info.session_timeout = session->timeout;
427   info.address = session->address;
428   plugin->sic (plugin->sic_cls,
429                session,
430                &info);
431 }
432
433
434 /**
435  * Delete session @a s.
436  *
437  * @param s the session to delete
438  */
439 static void
440 client_delete_session (struct GNUNET_ATS_Session *s)
441 {
442   struct HTTP_Client_Plugin *plugin = s->plugin;
443   struct HTTP_Message *pos;
444   struct HTTP_Message *next;
445   CURLMcode mret;
446
447   if (NULL != s->timeout_task)
448   {
449     GNUNET_SCHEDULER_cancel (s->timeout_task);
450     s->timeout_task = NULL;
451     s->timeout = GNUNET_TIME_UNIT_ZERO_ABS;
452   }
453   if (NULL != s->put_disconnect_task)
454   {
455     GNUNET_SCHEDULER_cancel (s->put_disconnect_task);
456     s->put_disconnect_task = NULL;
457   }
458   if (NULL != s->recv_wakeup_task)
459   {
460     GNUNET_SCHEDULER_cancel (s->recv_wakeup_task);
461     s->recv_wakeup_task = NULL;
462   }
463   GNUNET_assert (GNUNET_OK ==
464                  GNUNET_CONTAINER_multipeermap_remove (plugin->sessions,
465                                                        &s->address->peer,
466                                                        s));
467   if (NULL != s->put.easyhandle)
468   {
469     LOG (GNUNET_ERROR_TYPE_DEBUG,
470          "Session %p/request %p: disconnecting PUT request to peer `%s'\n",
471          s,
472          s->put.easyhandle,
473          GNUNET_i2s (&s->address->peer));
474
475     /* remove curl handle from multi handle */
476     mret = curl_multi_remove_handle (plugin->curl_multi_handle,
477                                      s->put.easyhandle);
478     GNUNET_break (CURLM_OK == mret);
479     curl_easy_cleanup (s->put.easyhandle);
480     GNUNET_assert (plugin->cur_requests > 0);
481     plugin->cur_requests--;
482     s->put.easyhandle = NULL;
483   }
484   if (NULL != s->get.easyhandle)
485   {
486     LOG (GNUNET_ERROR_TYPE_DEBUG,
487          "Session %p/request %p: disconnecting GET request to peer `%s'\n",
488          s, s->get.easyhandle,
489          GNUNET_i2s (&s->address->peer));
490     /* remove curl handle from multi handle */
491     mret = curl_multi_remove_handle (plugin->curl_multi_handle,
492                                      s->get.easyhandle);
493     GNUNET_break (CURLM_OK == mret);
494     curl_easy_cleanup (s->get.easyhandle);
495     GNUNET_assert (plugin->cur_requests > 0);
496     plugin->cur_requests--;
497     s->get.easyhandle = NULL;
498   }
499
500   GNUNET_STATISTICS_set (plugin->env->stats,
501                          HTTP_STAT_STR_CONNECTIONS,
502                          plugin->cur_requests,
503                          GNUNET_NO);
504   next = s->msg_head;
505   while (NULL != (pos = next))
506   {
507     next = pos->next;
508     GNUNET_CONTAINER_DLL_remove (s->msg_head,
509                                  s->msg_tail,
510                                  pos);
511     GNUNET_assert (0 < s->msgs_in_queue);
512     s->msgs_in_queue--;
513     GNUNET_assert (pos->size <= s->bytes_in_queue);
514     s->bytes_in_queue -= pos->size;
515     if (NULL != pos->transmit_cont)
516       pos->transmit_cont (pos->transmit_cont_cls,
517                           &s->address->peer,
518                           GNUNET_SYSERR,
519                           pos->size,
520                           pos->pos + s->overhead);
521     s->overhead = 0;
522     GNUNET_free (pos);
523   }
524   GNUNET_assert (0 == s->msgs_in_queue);
525   GNUNET_assert (0 == s->bytes_in_queue);
526   notify_session_monitor (plugin,
527                           s,
528                           GNUNET_TRANSPORT_SS_DONE);
529   if (NULL != s->msg_tk)
530   {
531     GNUNET_MST_destroy (s->msg_tk);
532     s->msg_tk = NULL;
533   }
534   GNUNET_HELLO_address_free (s->address);
535   GNUNET_free (s->url);
536   GNUNET_free (s);
537 }
538
539
540 /**
541  * Increment session timeout due to activity for session @a s.
542  *
543  * @param s the session
544  */
545 static void
546 client_reschedule_session_timeout (struct GNUNET_ATS_Session *s)
547 {
548   GNUNET_assert (NULL != s->timeout_task);
549   s->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
550 }
551
552
553 /**
554  * Task performing curl operations
555  *
556  * @param cls plugin as closure
557  * @param tc gnunet scheduler task context
558  */
559 static void
560 client_run (void *cls);
561
562
563 /**
564  * Function setting up file descriptors and scheduling task to run
565  *
566  * @param plugin the plugin as closure
567  * @param now schedule task in 1ms, regardless of what curl may say
568  * @return #GNUNET_SYSERR for hard failure, #GNUNET_OK for ok
569  */
570 static int
571 client_schedule (struct HTTP_Client_Plugin *plugin,
572                  int now)
573 {
574   fd_set rs;
575   fd_set ws;
576   fd_set es;
577   int max;
578   struct GNUNET_NETWORK_FDSet *grs;
579   struct GNUNET_NETWORK_FDSet *gws;
580   long to;
581   CURLMcode mret;
582   struct GNUNET_TIME_Relative timeout;
583
584   /* Cancel previous scheduled task */
585   if (plugin->client_perform_task != NULL)
586   {
587     GNUNET_SCHEDULER_cancel (plugin->client_perform_task);
588     plugin->client_perform_task = NULL;
589   }
590   max = -1;
591   FD_ZERO (&rs);
592   FD_ZERO (&ws);
593   FD_ZERO (&es);
594   mret = curl_multi_fdset (plugin->curl_multi_handle, &rs, &ws, &es, &max);
595   if (mret != CURLM_OK)
596   {
597     LOG (GNUNET_ERROR_TYPE_ERROR,
598          _("%s failed at %s:%d: `%s'\n"),
599          "curl_multi_fdset",
600          __FILE__,
601          __LINE__,
602          curl_multi_strerror (mret));
603     return GNUNET_SYSERR;
604   }
605   mret = curl_multi_timeout (plugin->curl_multi_handle, &to);
606   if (-1 == to)
607     timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1);
608   else
609     timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, to);
610   if (now == GNUNET_YES)
611     timeout = GNUNET_TIME_UNIT_MILLISECONDS;
612
613   if (CURLM_OK != mret)
614   {
615     LOG (GNUNET_ERROR_TYPE_ERROR,
616                 _("%s failed at %s:%d: `%s'\n"),
617                 "curl_multi_timeout", __FILE__, __LINE__,
618                 curl_multi_strerror (mret));
619     return GNUNET_SYSERR;
620   }
621
622   grs = GNUNET_NETWORK_fdset_create ();
623   gws = GNUNET_NETWORK_fdset_create ();
624   GNUNET_NETWORK_fdset_copy_native (grs, &rs, max + 1);
625   GNUNET_NETWORK_fdset_copy_native (gws, &ws, max + 1);
626
627   /* Schedule task to run when select is ready to read or write */
628   plugin->client_perform_task =
629       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
630                                    timeout, grs, gws,
631                                    &client_run, plugin);
632   GNUNET_NETWORK_fdset_destroy (gws);
633   GNUNET_NETWORK_fdset_destroy (grs);
634   return GNUNET_OK;
635 }
636
637
638 #if VERBOSE_CURL
639 /**
640  * Loggging function
641  *
642  * @param curl the curl easy handle
643  * @param type message type
644  * @param data data to log, NOT a 0-terminated string
645  * @param size data length
646  * @param cls the closure
647  * @return always 0
648  */
649 static int
650 client_log (CURL *curl,
651             curl_infotype type,
652             const char *data,
653             size_t size,
654             void *cls)
655 {
656   struct RequestHandle *ch = cls;
657   const char *ttype = "UNSPECIFIED";
658   char text[size + 2];
659
660   if (! ((CURLINFO_TEXT == type) ||
661          (CURLINFO_HEADER_IN == type) ||
662          (CURLINFO_HEADER_OUT == type)))
663     return 0;
664   switch (type)
665   {
666   case CURLINFO_TEXT:
667     ttype = "TEXT";
668     break;
669   case CURLINFO_HEADER_IN:
670     ttype = "HEADER_IN";
671     break;
672   case CURLINFO_HEADER_OUT:
673     ttype = "HEADER_OUT";
674     /* Overhead*/
675     GNUNET_assert (NULL != ch);
676     GNUNET_assert (NULL != ch->easyhandle);
677     GNUNET_assert (NULL != ch->s);
678     ch->s->overhead += size;
679     break;
680   default:
681     ttype = "UNSPECIFIED";
682     break;
683   }
684   GNUNET_memcpy (text, data, size);
685   if (text[size - 1] == '\n')
686   {
687     text[size] = '\0';
688   }
689   else
690   {
691     text[size] = '\n';
692     text[size + 1] = '\0';
693   }
694   LOG (GNUNET_ERROR_TYPE_DEBUG,
695        "Request %p %s: %s",
696        ch->easyhandle,
697        ttype,
698        text);
699   return 0;
700 }
701 #endif
702
703 /**
704  * Connect GET request
705  *
706  * @param s the session to connect
707  * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
708  */
709 static int
710 client_connect_get (struct GNUNET_ATS_Session *s);
711
712
713 /**
714  * Connect a HTTP put request
715  *
716  * @param s the session to connect
717  * @return #GNUNET_SYSERR for hard failure, #GNUNET_OK for success
718  */
719 static int
720 client_connect_put (struct GNUNET_ATS_Session *s);
721
722
723 /**
724  * Function that can be used by the transport service to transmit
725  * a message using the plugin.   Note that in the case of a
726  * peer disconnecting, the continuation MUST be called
727  * prior to the disconnect notification itself.  This function
728  * will be called with this peer's HELLO message to initiate
729  * a fresh connection to another peer.
730  *
731  * @param cls closure
732  * @param s which session must be used
733  * @param msgbuf the message to transmit
734  * @param msgbuf_size number of bytes in @a msgbuf
735  * @param priority how important is the message (most plugins will
736  *                 ignore message priority and just FIFO)
737  * @param to how long to wait at most for the transmission (does not
738  *                require plugins to discard the message after the timeout,
739  *                just advisory for the desired delay; most plugins will ignore
740  *                this as well)
741  * @param cont continuation to call once the message has
742  *        been transmitted (or if the transport is ready
743  *        for the next transmission call; or if the
744  *        peer disconnected...); can be NULL
745  * @param cont_cls closure for @a cont
746  * @return number of bytes used (on the physical network, with overheads);
747  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
748  *         and does NOT mean that the message was not transmitted (DV)
749  */
750 static ssize_t
751 http_client_plugin_send (void *cls,
752                          struct GNUNET_ATS_Session *s,
753                          const char *msgbuf,
754                          size_t msgbuf_size,
755                          unsigned int priority,
756                          struct GNUNET_TIME_Relative to,
757                          GNUNET_TRANSPORT_TransmitContinuation cont,
758                          void *cont_cls)
759 {
760   struct HTTP_Client_Plugin *plugin = cls;
761   struct HTTP_Message *msg;
762   char *stat_txt;
763
764   LOG (GNUNET_ERROR_TYPE_DEBUG,
765        "Session %p/request %p: Sending message with %u to peer `%s' \n",
766        s,
767        s->put.easyhandle,
768        msgbuf_size,
769        GNUNET_i2s (&s->address->peer));
770
771   /* create new message and schedule */
772   msg = GNUNET_malloc (sizeof (struct HTTP_Message) + msgbuf_size);
773   msg->size = msgbuf_size;
774   msg->buf = (char *) &msg[1];
775   msg->transmit_cont = cont;
776   msg->transmit_cont_cls = cont_cls;
777   GNUNET_memcpy (msg->buf,
778           msgbuf,
779           msgbuf_size);
780   GNUNET_CONTAINER_DLL_insert_tail (s->msg_head,
781                                     s->msg_tail,
782                                     msg);
783   s->msgs_in_queue++;
784   s->bytes_in_queue += msg->size;
785
786   GNUNET_asprintf (&stat_txt,
787                    "# bytes currently in %s_client buffers",
788                    plugin->protocol);
789   GNUNET_STATISTICS_update (plugin->env->stats,
790                             stat_txt, msgbuf_size, GNUNET_NO);
791   GNUNET_free (stat_txt);
792   notify_session_monitor (plugin,
793                           s,
794                           GNUNET_TRANSPORT_SS_UPDATE);
795   if (H_TMP_DISCONNECTING == s->put.state)
796   {
797     /* PUT request is currently getting disconnected */
798     s->put.state = H_TMP_RECONNECT_REQUIRED;
799     LOG (GNUNET_ERROR_TYPE_DEBUG,
800          "Session %p/request %p: currently disconnecting, reconnecting immediately\n",
801          s,
802          s->put.easyhandle);
803     return msgbuf_size;
804   }
805   if (H_PAUSED == s->put.state)
806   {
807     /* PUT request was paused, unpause */
808     GNUNET_assert (s->put_disconnect_task != NULL);
809     GNUNET_SCHEDULER_cancel (s->put_disconnect_task);
810     s->put_disconnect_task = NULL;
811     LOG (GNUNET_ERROR_TYPE_DEBUG,
812          "Session %p/request %p: unpausing request\n",
813          s, s->put.easyhandle);
814     s->put.state = H_CONNECTED;
815     if (NULL != s->put.easyhandle)
816       curl_easy_pause (s->put.easyhandle, CURLPAUSE_CONT);
817   }
818   else if (H_TMP_DISCONNECTED == s->put.state)
819   {
820     /* PUT request was disconnected, reconnect */
821     LOG (GNUNET_ERROR_TYPE_DEBUG, "Session %p: Reconnecting PUT request\n", s);
822     GNUNET_break (NULL == s->put.easyhandle);
823     if (GNUNET_SYSERR == client_connect_put (s))
824     {
825       /* Could not reconnect */
826       http_client_plugin_session_disconnect (plugin, s);
827       return GNUNET_SYSERR;
828     }
829   }
830   client_schedule (s->plugin, GNUNET_YES);
831   return msgbuf_size;
832 }
833
834
835 /**
836  * Disconnect a session
837  *
838  * @param cls the `struct HTTP_Client_Plugin *`
839  * @param s session
840  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
841  */
842 static int
843 http_client_plugin_session_disconnect (void *cls,
844                                        struct GNUNET_ATS_Session *s)
845 {
846   struct HTTP_Client_Plugin *plugin = cls;
847
848   LOG (GNUNET_ERROR_TYPE_DEBUG,
849        "Session %p: notifying transport about ending session\n",
850        s);
851   plugin->env->session_end (plugin->env->cls,
852                             s->address,
853                             s);
854   client_delete_session (s);
855
856   /* Re-schedule since handles have changed */
857   if (NULL != plugin->client_perform_task)
858   {
859     GNUNET_SCHEDULER_cancel (plugin->client_perform_task);
860     plugin->client_perform_task = NULL;
861   }
862   client_schedule (plugin, GNUNET_YES);
863
864   return GNUNET_OK;
865 }
866
867
868 /**
869  * Function that is called to get the keepalive factor.
870  * #GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT is divided by this number to
871  * calculate the interval between keepalive packets.
872  *
873  * @param cls closure with the `struct Plugin`
874  * @return keepalive factor
875  */
876 static unsigned int
877 http_client_query_keepalive_factor (void *cls)
878 {
879   return 3;
880 }
881
882
883 /**
884  * Callback to destroys all sessions on exit.
885  *
886  * @param cls the `struct HTTP_Client_Plugin *`
887  * @param peer identity of the peer
888  * @param value the `struct GNUNET_ATS_Session *`
889  * @return #GNUNET_OK (continue iterating)
890  */
891 static int
892 destroy_session_cb (void *cls,
893                     const struct GNUNET_PeerIdentity *peer,
894                     void *value)
895 {
896   struct HTTP_Client_Plugin *plugin = cls;
897   struct GNUNET_ATS_Session *session = value;
898
899   http_client_plugin_session_disconnect (plugin, session);
900   return GNUNET_OK;
901 }
902
903
904 /**
905  * Function that can be used to force the plugin to disconnect
906  * from the given peer and cancel all previous transmissions
907  * (and their continuationc).
908  *
909  * @param cls closure
910  * @param target peer from which to disconnect
911  */
912 static void
913 http_client_plugin_peer_disconnect (void *cls,
914                                     const struct GNUNET_PeerIdentity *target)
915 {
916   struct HTTP_Client_Plugin *plugin = cls;
917
918   LOG (GNUNET_ERROR_TYPE_DEBUG,
919        "Transport tells me to disconnect `%s'\n",
920        GNUNET_i2s (target));
921   GNUNET_CONTAINER_multipeermap_get_multiple (plugin->sessions,
922                                               target,
923                                               &destroy_session_cb,
924                                               plugin);
925 }
926
927
928 /**
929  * Closure for #session_lookup_client_by_address().
930  */
931 struct GNUNET_ATS_SessionClientCtx
932 {
933   /**
934    * Address we are looking for.
935    */
936   const struct GNUNET_HELLO_Address *address;
937
938   /**
939    * Session that was found.
940    */
941   struct GNUNET_ATS_Session *ret;
942 };
943
944
945 /**
946  * Locate the seession object for a given address.
947  *
948  * @param cls the `struct GNUNET_ATS_SessionClientCtx *`
949  * @param key peer identity
950  * @param value the `struct GNUNET_ATS_Session` to check
951  * @return #GNUNET_NO if found, #GNUNET_OK if not
952  */
953 static int
954 session_lookup_client_by_address (void *cls,
955                                   const struct GNUNET_PeerIdentity *key,
956                                   void *value)
957 {
958   struct GNUNET_ATS_SessionClientCtx *sc_ctx = cls;
959   struct GNUNET_ATS_Session *s = value;
960
961   if (0 == GNUNET_HELLO_address_cmp (sc_ctx->address,
962                                      s->address))
963   {
964     sc_ctx->ret = s;
965     return GNUNET_NO;
966   }
967   return GNUNET_YES;
968 }
969
970
971 /**
972  * Check if a sessions exists for an specific address
973  *
974  * @param plugin the plugin
975  * @param address the address
976  * @return the session or NULL
977  */
978 static struct GNUNET_ATS_Session *
979 client_lookup_session (struct HTTP_Client_Plugin *plugin,
980                        const struct GNUNET_HELLO_Address *address)
981 {
982   struct GNUNET_ATS_SessionClientCtx sc_ctx;
983
984   sc_ctx.address = address;
985   sc_ctx.ret = NULL;
986   GNUNET_CONTAINER_multipeermap_iterate (plugin->sessions,
987                                          &session_lookup_client_by_address,
988                                          &sc_ctx);
989   return sc_ctx.ret;
990 }
991
992
993 /**
994  * When we have nothing to transmit, we pause the HTTP PUT
995  * after a while (so that gnurl stops asking).  This task
996  * is the delayed task that actually disconnects the PUT.
997  *
998  * @param cls the `struct GNUNET_ATS_Session *` with the put
999  */
1000 static void
1001 client_put_disconnect (void *cls)
1002 {
1003   struct GNUNET_ATS_Session *s = cls;
1004
1005   s->put_disconnect_task = NULL;
1006   LOG (GNUNET_ERROR_TYPE_DEBUG,
1007        "Session %p/request %p: will be disconnected due to no activity\n",
1008        s, s->put.easyhandle);
1009   s->put.state = H_TMP_DISCONNECTING;
1010   if (NULL != s->put.easyhandle)
1011     curl_easy_pause (s->put.easyhandle,
1012                      CURLPAUSE_CONT);
1013   client_schedule (s->plugin, GNUNET_YES);
1014 }
1015
1016
1017 /**
1018  * Callback method used with libcurl
1019  * Method is called when libcurl needs to read data during sending
1020  *
1021  * @param stream pointer where to write data
1022  * @param size size of an individual element
1023  * @param nmemb count of elements that can be written to the buffer
1024  * @param cls our `struct GNUNET_ATS_Session`
1025  * @return bytes written to stream, returning 0 will terminate request!
1026  */
1027 static size_t
1028 client_send_cb (void *stream,
1029                 size_t size,
1030                 size_t nmemb,
1031                 void *cls)
1032 {
1033   struct GNUNET_ATS_Session *s = cls;
1034   struct HTTP_Client_Plugin *plugin = s->plugin;
1035   struct HTTP_Message *msg = s->msg_head;
1036   size_t len;
1037   char *stat_txt;
1038
1039   if (H_TMP_DISCONNECTING == s->put.state)
1040   {
1041     LOG (GNUNET_ERROR_TYPE_DEBUG,
1042          "Session %p/request %p: disconnect due to inactivity\n",
1043          s, s->put.easyhandle);
1044     return 0;
1045   }
1046
1047   if (NULL == msg)
1048   {
1049     if (GNUNET_YES == plugin->emulate_xhr)
1050     {
1051       LOG (GNUNET_ERROR_TYPE_DEBUG,
1052            "Session %p/request %p: PUT request finished\n",
1053            s,
1054            s->put.easyhandle);
1055       s->put.state = H_TMP_DISCONNECTING;
1056       return 0;
1057     }
1058
1059     /* We have nothing to send, so pause PUT request */
1060     LOG (GNUNET_ERROR_TYPE_DEBUG,
1061          "Session %p/request %p: nothing to send, suspending\n",
1062          s,
1063          s->put.easyhandle);
1064     s->put_disconnect_task
1065       = GNUNET_SCHEDULER_add_delayed (PUT_DISCONNECT_TIMEOUT,
1066                                       &client_put_disconnect,
1067                                       s);
1068     s->put.state = H_PAUSED;
1069     return CURL_READFUNC_PAUSE;
1070   }
1071   /* data to send */
1072   GNUNET_assert (msg->pos < msg->size);
1073   /* calculate how much fits in buffer */
1074   len = GNUNET_MIN (msg->size - msg->pos,
1075                     size * nmemb);
1076   GNUNET_memcpy (stream,
1077                  &msg->buf[msg->pos],
1078                  len);
1079   msg->pos += len;
1080   if (msg->pos == msg->size)
1081   {
1082     LOG (GNUNET_ERROR_TYPE_DEBUG,
1083          "Session %p/request %p: sent message with %u bytes sent, removing message from queue\n",
1084          s,
1085          s->put.easyhandle,
1086          msg->size,
1087          msg->pos);
1088     /* Calling transmit continuation  */
1089     GNUNET_CONTAINER_DLL_remove (s->msg_head,
1090                                  s->msg_tail,
1091                                  msg);
1092     GNUNET_assert (0 < s->msgs_in_queue);
1093     s->msgs_in_queue--;
1094     GNUNET_assert (msg->size <= s->bytes_in_queue);
1095     s->bytes_in_queue -= msg->size;
1096     if (NULL != msg->transmit_cont)
1097       msg->transmit_cont (msg->transmit_cont_cls,
1098                           &s->address->peer,
1099                           GNUNET_OK,
1100                           msg->size,
1101                           msg->size + s->overhead);
1102     s->overhead = 0;
1103     GNUNET_free (msg);
1104   }
1105   notify_session_monitor (plugin,
1106                           s,
1107                           GNUNET_TRANSPORT_SS_UPDATE);
1108   GNUNET_asprintf (&stat_txt,
1109                    "# bytes currently in %s_client buffers",
1110                    plugin->protocol);
1111   GNUNET_STATISTICS_update (plugin->env->stats,
1112                             stat_txt,
1113                             - len,
1114                             GNUNET_NO);
1115   GNUNET_free (stat_txt);
1116   GNUNET_asprintf (&stat_txt,
1117                    "# bytes transmitted via %s_client",
1118                    plugin->protocol);
1119   GNUNET_STATISTICS_update (plugin->env->stats,
1120                             stat_txt,
1121                             len,
1122                             GNUNET_NO);
1123   GNUNET_free (stat_txt);
1124   return len;
1125 }
1126
1127
1128 /**
1129  * Wake up a curl handle which was suspended
1130  *
1131  * @param cls the session
1132  */
1133 static void
1134 client_wake_up (void *cls)
1135 {
1136   struct GNUNET_ATS_Session *s = cls;
1137
1138   s->recv_wakeup_task = NULL;
1139   LOG (GNUNET_ERROR_TYPE_DEBUG,
1140        "Session %p/request %p: Waking up GET handle\n",
1141        s, s->get.easyhandle);
1142   if (H_PAUSED == s->put.state)
1143   {
1144     /* PUT request was paused, unpause */
1145     GNUNET_assert (s->put_disconnect_task != NULL);
1146     GNUNET_SCHEDULER_cancel (s->put_disconnect_task);
1147     s->put_disconnect_task = NULL;
1148     s->put.state = H_CONNECTED;
1149     if (NULL != s->put.easyhandle)
1150       curl_easy_pause (s->put.easyhandle, CURLPAUSE_CONT);
1151   }
1152   if (NULL != s->get.easyhandle)
1153     curl_easy_pause (s->get.easyhandle, CURLPAUSE_CONT);
1154 }
1155
1156
1157 /**
1158  * Callback for message stream tokenizer
1159  *
1160  * @param cls the session
1161  * @param message the message received
1162  * @return always #GNUNET_OK
1163  */
1164 static int
1165 client_receive_mst_cb (void *cls,
1166                        const struct GNUNET_MessageHeader *message)
1167 {
1168   struct GNUNET_ATS_Session *s = cls;
1169   struct HTTP_Client_Plugin *plugin;
1170   struct GNUNET_TIME_Relative delay;
1171   char *stat_txt;
1172
1173   plugin = s->plugin;
1174   delay = s->plugin->env->receive (plugin->env->cls,
1175                                    s->address,
1176                                    s,
1177                                    message);
1178   GNUNET_asprintf (&stat_txt,
1179                    "# bytes received via %s_client",
1180                    plugin->protocol);
1181   GNUNET_STATISTICS_update (plugin->env->stats,
1182                             stat_txt,
1183                             ntohs (message->size),
1184                             GNUNET_NO);
1185   GNUNET_free (stat_txt);
1186
1187   s->next_receive = GNUNET_TIME_relative_to_absolute (delay);
1188   if (GNUNET_TIME_absolute_get ().abs_value_us < s->next_receive.abs_value_us)
1189   {
1190     LOG (GNUNET_ERROR_TYPE_DEBUG,
1191          "Client: peer `%s' address `%s' next read delayed for %s\n",
1192          GNUNET_i2s (&s->address->peer),
1193          http_common_plugin_address_to_string (s->plugin->protocol,
1194                                                s->address->address,
1195                                                s->address->address_length),
1196          GNUNET_STRINGS_relative_time_to_string (delay,
1197                                                  GNUNET_YES));
1198   }
1199   client_reschedule_session_timeout (s);
1200   return GNUNET_OK;
1201 }
1202
1203
1204 /**
1205  * Callback method used with libcurl when data for a PUT request are
1206  * received.  We do not expect data here, so we just discard it.
1207  *
1208  * @param stream pointer where to write data
1209  * @param size size of an individual element
1210  * @param nmemb count of elements that can be written to the buffer
1211  * @param cls destination pointer, passed to the libcurl handle
1212  * @return bytes read from stream
1213  */
1214 static size_t
1215 client_receive_put (void *stream,
1216                     size_t size,
1217                     size_t nmemb,
1218                     void *cls)
1219 {
1220   return size * nmemb;
1221 }
1222
1223
1224 /**
1225  * Callback method used with libcurl when data for a GET request are
1226  * received. Forward to MST
1227  *
1228  * @param stream pointer where to write data
1229  * @param size size of an individual element
1230  * @param nmemb count of elements that can be written to the buffer
1231  * @param cls destination pointer, passed to the libcurl handle
1232  * @return bytes read from stream
1233  */
1234 static size_t
1235 client_receive (void *stream,
1236                 size_t size,
1237                 size_t nmemb,
1238                 void *cls)
1239 {
1240   struct GNUNET_ATS_Session *s = cls;
1241   struct GNUNET_TIME_Absolute now;
1242   size_t len = size * nmemb;
1243
1244   LOG (GNUNET_ERROR_TYPE_DEBUG,
1245        "Session %p / request %p: Received %u bytes from peer `%s'\n",
1246        s,
1247        s->get.easyhandle,
1248        len,
1249        GNUNET_i2s (&s->address->peer));
1250   now = GNUNET_TIME_absolute_get ();
1251   if (now.abs_value_us < s->next_receive.abs_value_us)
1252   {
1253     struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
1254     struct GNUNET_TIME_Relative delta
1255       = GNUNET_TIME_absolute_get_difference (now, s->next_receive);
1256
1257     LOG (GNUNET_ERROR_TYPE_DEBUG,
1258          "Session %p / request %p: No inbound bandwidth available! Next read was delayed for %s\n",
1259          s,
1260          s->get.easyhandle,
1261          GNUNET_STRINGS_relative_time_to_string (delta,
1262                                                  GNUNET_YES));
1263     if (s->recv_wakeup_task != NULL)
1264     {
1265       GNUNET_SCHEDULER_cancel (s->recv_wakeup_task);
1266       s->recv_wakeup_task = NULL;
1267     }
1268     s->recv_wakeup_task
1269       = GNUNET_SCHEDULER_add_delayed (delta,
1270                                       &client_wake_up,
1271                                       s);
1272     return CURL_WRITEFUNC_PAUSE;
1273   }
1274   if (NULL == s->msg_tk)
1275     s->msg_tk = GNUNET_MST_create (&client_receive_mst_cb,
1276                                    s);
1277   GNUNET_MST_from_buffer (s->msg_tk,
1278                           stream,
1279                           len,
1280                           GNUNET_NO,
1281                           GNUNET_NO);
1282   return len;
1283 }
1284
1285
1286 /**
1287  * Task performing curl operations
1288  *
1289  * @param cls plugin as closure
1290  */
1291 static void
1292 client_run (void *cls)
1293 {
1294   struct HTTP_Client_Plugin *plugin = cls;
1295   int running;
1296   long http_statuscode;
1297   CURLMcode mret;
1298   CURLMsg *msg;
1299   int put_request; /* GNUNET_YES if easy handle is put, GNUNET_NO for get */
1300   int msgs_left;
1301
1302   plugin->client_perform_task = NULL;
1303   /* While data are available or timeouts occured */
1304   do
1305   {
1306     running = 0;
1307     /* Perform operations for all handles */
1308     mret = curl_multi_perform (plugin->curl_multi_handle, &running);
1309
1310     /* Get additional information for all handles */
1311     while (NULL != (msg = curl_multi_info_read (plugin->curl_multi_handle, &msgs_left)))
1312     {
1313       CURL *easy_h = msg->easy_handle;
1314       struct GNUNET_ATS_Session *s = NULL;
1315       char *d = NULL; /* curl requires 'd' to be a 'char *' */
1316
1317       GNUNET_assert (NULL != easy_h);
1318
1319       /* Obtain session from easy handle */
1320       GNUNET_assert (CURLE_OK == curl_easy_getinfo (easy_h, CURLINFO_PRIVATE, &d));
1321       s = (struct GNUNET_ATS_Session *) d;
1322       GNUNET_assert (NULL != s);
1323
1324       if (msg->msg != CURLMSG_DONE)
1325         continue; /* This should not happen */
1326
1327       /* Get HTTP response code */
1328       GNUNET_break (CURLE_OK == curl_easy_getinfo (easy_h,
1329           CURLINFO_RESPONSE_CODE, &http_statuscode));
1330
1331       if (easy_h == s->put.easyhandle)
1332         put_request = GNUNET_YES;
1333       else
1334         put_request = GNUNET_NO;
1335
1336       /* Log status of terminated request */
1337       if  ((0 != msg->data.result) || (http_statuscode != 200))
1338         LOG (GNUNET_ERROR_TYPE_DEBUG,
1339              "Session %p/request %p: %s request to `%s' ended with status %i reason %i: `%s'\n",
1340              s, msg->easy_handle,
1341              (GNUNET_YES == put_request) ? "PUT" : "GET",
1342              GNUNET_i2s (&s->address->peer),
1343              http_statuscode,
1344              msg->data.result,
1345              curl_easy_strerror (msg->data.result));
1346       else
1347         LOG (GNUNET_ERROR_TYPE_DEBUG,
1348              "Session %p/request %p: %s request to `%s' ended normal\n",
1349              s, msg->easy_handle,
1350              (GNUNET_YES == put_request) ? "PUT" : "GET",
1351              GNUNET_i2s (&s->address->peer));
1352
1353       /* Remove easy handle from multi handle */
1354       curl_multi_remove_handle (plugin->curl_multi_handle, easy_h);
1355
1356       /* Clean up easy handle */
1357       curl_easy_cleanup (easy_h);
1358
1359       /* Remove information */
1360       GNUNET_assert (plugin->cur_requests > 0);
1361       plugin->cur_requests--;
1362       LOG  (GNUNET_ERROR_TYPE_INFO,
1363           "%s request to %s done, number of requests decreased to %u\n",
1364           (GNUNET_YES == put_request) ? "PUT" : "GET",
1365           s->url,
1366           plugin->cur_requests);
1367
1368       if (GNUNET_YES == put_request)
1369       {
1370         /* Clean up a PUT request */
1371         s->put.easyhandle = NULL;
1372         s->put.s = NULL;
1373
1374         switch (s->put.state) {
1375           case H_NOT_CONNECTED:
1376           case H_DISCONNECTED:
1377           case H_TMP_DISCONNECTED:
1378             /* This must not happen */
1379             GNUNET_break (0);
1380             break;
1381           case H_TMP_RECONNECT_REQUIRED:
1382             /* Transport called send while disconnect in progess, reconnect */
1383             if (GNUNET_SYSERR == client_connect_put (s))
1384             {
1385               /* Reconnect failed, disconnect session */
1386               http_client_plugin_session_disconnect (plugin, s);
1387             }
1388             break;
1389           case H_TMP_DISCONNECTING:
1390             /* PUT gets temporarily disconnected */
1391             s->put.state = H_TMP_DISCONNECTED;
1392             break;
1393           case H_PAUSED:
1394           case H_CONNECTED:
1395             /* PUT gets permanently disconnected */
1396             s->put.state = H_DISCONNECTED;
1397             http_client_plugin_session_disconnect (plugin, s);
1398             break;
1399           default:
1400             GNUNET_break (0);
1401             break;
1402         }
1403       }
1404       else if (GNUNET_NO == put_request)
1405       {
1406         /* Clean up a GET request */
1407         s->get.easyhandle = NULL;
1408         s->get.s = NULL;
1409
1410         /* If we are emulating an XHR client we need to make another GET
1411          * request.
1412          */
1413         if (GNUNET_YES == plugin->emulate_xhr)
1414         {
1415           if (GNUNET_SYSERR == client_connect_get (s))
1416             http_client_plugin_session_disconnect (plugin, s);
1417         }
1418         else
1419         {
1420           /* GET request was terminated, so disconnect session */
1421           http_client_plugin_session_disconnect (plugin, s);
1422         }
1423       }
1424       else
1425         GNUNET_break (0); /* Must not happen */
1426
1427       GNUNET_STATISTICS_set (plugin->env->stats,
1428                              HTTP_STAT_STR_CONNECTIONS,
1429                              plugin->cur_requests,
1430                              GNUNET_NO);
1431     }
1432   }
1433   while (mret == CURLM_CALL_MULTI_PERFORM);
1434   client_schedule (plugin, GNUNET_NO);
1435 }
1436
1437
1438 #ifdef TCP_STEALTH
1439 /**
1440  * Open TCP socket with TCP STEALTH enabled.
1441  *
1442  * @param clientp our `struct GNUNET_ATS_Session *`
1443  * @param purpose why does curl want to open a socket
1444  * @param address what kind of socket does curl want to have opened?
1445  * @return opened socket
1446  */
1447 static curl_socket_t
1448 open_tcp_stealth_socket_cb (void *clientp,
1449                             curlsocktype purpose,
1450                             struct curl_sockaddr *address)
1451 {
1452   struct GNUNET_ATS_Session *s = clientp;
1453   int ret;
1454
1455   switch (purpose)
1456   {
1457   case CURLSOCKTYPE_IPCXN:
1458     ret = socket (address->family,
1459                   address->socktype,
1460                   address->protocol);
1461     if (-1 == ret)
1462       return CURL_SOCKET_BAD;
1463     if ( ( (SOCK_STREAM != address->socktype) ||
1464            ( (0 != address->protocol) &&
1465              (IPPROTO_TCP != address->protocol))) )
1466       return (curl_socket_t) ret;
1467     if ( (0 != setsockopt (ret,
1468                            IPPROTO_TCP,
1469                            TCP_STEALTH,
1470                            &s->address->peer,
1471                            sizeof (struct GNUNET_PeerIdentity))) )
1472     {
1473       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1474                   _("TCP_STEALTH not supported on this platform.\n"));
1475       (void) close (ret);
1476       return CURL_SOCKET_BAD;
1477     }
1478     return (curl_socket_t) ret;
1479   case CURLSOCKTYPE_ACCEPT:
1480     GNUNET_break (0);
1481     return CURL_SOCKET_BAD;
1482     break;
1483   case CURLSOCKTYPE_LAST:
1484     GNUNET_break (0);
1485     return CURL_SOCKET_BAD;
1486   default:
1487     GNUNET_break (0);
1488     return CURL_SOCKET_BAD;
1489   }
1490 }
1491 #endif
1492
1493
1494 /**
1495  * Connect GET request for a session
1496  *
1497  * @param s the session to connect
1498  * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
1499  */
1500 static int
1501 client_connect_get (struct GNUNET_ATS_Session *s)
1502 {
1503   CURLMcode mret;
1504   struct HttpAddress *ha;
1505   uint32_t options;
1506
1507   ha = (struct HttpAddress *) s->address->address;
1508   options = ntohl (ha->options);
1509   /* create get request */
1510   s->get.easyhandle = curl_easy_init ();
1511   s->get.s = s;
1512   if (0 != (options & HTTP_OPTIONS_TCP_STEALTH))
1513   {
1514 #ifdef TCP_STEALTH
1515     curl_easy_setopt (s->get.easyhandle,
1516                       CURLOPT_OPENSOCKETFUNCTION,
1517                       &open_tcp_stealth_socket_cb);
1518     curl_easy_setopt (s->get.easyhandle,
1519                       CURLOPT_OPENSOCKETDATA,
1520                       s);
1521 #else
1522     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1523                 "Cannot connect, TCP STEALTH needed and not supported by kernel.\n");
1524     curl_easy_cleanup (s->get.easyhandle);
1525     s->get.easyhandle = NULL;
1526     s->get.s = NULL;
1527     return GNUNET_SYSERR;
1528 #endif
1529   }
1530
1531 #if VERBOSE_CURL
1532   curl_easy_setopt (s->get.easyhandle,
1533                     CURLOPT_VERBOSE,
1534                     1L);
1535   curl_easy_setopt (s->get.easyhandle,
1536                     CURLOPT_DEBUGFUNCTION,
1537                     &client_log);
1538   curl_easy_setopt (s->get.easyhandle,
1539                     CURLOPT_DEBUGDATA,
1540                     &s->get);
1541 #endif
1542 #if BUILD_HTTPS
1543   curl_easy_setopt (s->get.easyhandle, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
1544   {
1545     if (HTTP_OPTIONS_VERIFY_CERTIFICATE ==
1546         (options & HTTP_OPTIONS_VERIFY_CERTIFICATE))
1547     {
1548       curl_easy_setopt (s->get.easyhandle,
1549                         CURLOPT_SSL_VERIFYPEER, 1L);
1550       curl_easy_setopt (s->get.easyhandle,
1551                         CURLOPT_SSL_VERIFYHOST,
1552                         2L);
1553     }
1554     else
1555     {
1556       curl_easy_setopt (s->get.easyhandle,
1557                         CURLOPT_SSL_VERIFYPEER,
1558                         0L);
1559       curl_easy_setopt (s->get.easyhandle,
1560                         CURLOPT_SSL_VERIFYHOST,
1561                         0L);
1562     }
1563   }
1564   curl_easy_setopt (s->get.easyhandle,
1565                     CURLOPT_PROTOCOLS,
1566                     CURLPROTO_HTTPS);
1567   curl_easy_setopt (s->get.easyhandle,
1568                     CURLOPT_REDIR_PROTOCOLS,
1569                     CURLPROTO_HTTPS);
1570 #else
1571   curl_easy_setopt (s->get.easyhandle,
1572                     CURLOPT_PROTOCOLS,
1573                     CURLPROTO_HTTP);
1574   curl_easy_setopt (s->get.easyhandle,
1575                     CURLOPT_REDIR_PROTOCOLS,
1576                     CURLPROTO_HTTP);
1577 #endif
1578
1579   if (NULL != s->plugin->proxy_hostname)
1580   {
1581     curl_easy_setopt (s->get.easyhandle,
1582                       CURLOPT_PROXY,
1583                       s->plugin->proxy_hostname);
1584     curl_easy_setopt (s->get.easyhandle,
1585                       CURLOPT_PROXYTYPE,
1586                       s->plugin->proxytype);
1587     if (NULL != s->plugin->proxy_username)
1588       curl_easy_setopt (s->get.easyhandle,
1589                         CURLOPT_PROXYUSERNAME,
1590                         s->plugin->proxy_username);
1591     if (NULL != s->plugin->proxy_password)
1592       curl_easy_setopt (s->get.easyhandle,
1593                         CURLOPT_PROXYPASSWORD,
1594                         s->plugin->proxy_password);
1595     if (GNUNET_YES == s->plugin->proxy_use_httpproxytunnel)
1596       curl_easy_setopt (s->get.easyhandle,
1597                         CURLOPT_HTTPPROXYTUNNEL,
1598                         s->plugin->proxy_use_httpproxytunnel);
1599   }
1600
1601   if (GNUNET_YES == s->plugin->emulate_xhr)
1602   {
1603     char *url;
1604
1605     GNUNET_asprintf (&url,
1606                      "%s,1",
1607                      s->url);
1608     curl_easy_setopt (s->get.easyhandle,
1609                       CURLOPT_URL,
1610                       url);
1611     GNUNET_free(url);
1612   }
1613   else
1614   {
1615     curl_easy_setopt (s->get.easyhandle,
1616                       CURLOPT_URL,
1617                       s->url);
1618   }
1619   curl_easy_setopt (s->get.easyhandle,
1620                     CURLOPT_READFUNCTION,
1621                     &client_send_cb);
1622   curl_easy_setopt (s->get.easyhandle,
1623                     CURLOPT_READDATA,
1624                     s);
1625   curl_easy_setopt (s->get.easyhandle,
1626                     CURLOPT_WRITEFUNCTION,
1627                     &client_receive);
1628   curl_easy_setopt (s->get.easyhandle,
1629                     CURLOPT_WRITEDATA,
1630                     s);
1631   /* No timeout by default, timeout done with session timeout */
1632   curl_easy_setopt (s->get.easyhandle,
1633                     CURLOPT_TIMEOUT,
1634                     0L);
1635   curl_easy_setopt (s->get.easyhandle,
1636                     CURLOPT_PRIVATE, s);
1637   curl_easy_setopt (s->get.easyhandle,
1638                     CURLOPT_CONNECTTIMEOUT_MS,
1639                     (long) (HTTP_CLIENT_NOT_VALIDATED_TIMEOUT.rel_value_us / 1000LL));
1640   curl_easy_setopt (s->get.easyhandle, CURLOPT_BUFFERSIZE,
1641                     2 * GNUNET_MAX_MESSAGE_SIZE);
1642 #if CURL_TCP_NODELAY
1643   curl_easy_setopt (ps->recv_endpoint,
1644                     CURLOPT_TCP_NODELAY,
1645                     1L);
1646 #endif
1647   curl_easy_setopt (s->get.easyhandle,
1648                     CURLOPT_FOLLOWLOCATION,
1649                     0L);
1650
1651   mret = curl_multi_add_handle (s->plugin->curl_multi_handle,
1652                                 s->get.easyhandle);
1653   if (CURLM_OK != mret)
1654   {
1655     LOG (GNUNET_ERROR_TYPE_ERROR,
1656          "Session %p : Failed to add GET handle to multihandle: `%s'\n",
1657          s,
1658          curl_multi_strerror (mret));
1659     curl_easy_cleanup (s->get.easyhandle);
1660     s->get.easyhandle = NULL;
1661     s->get.s = NULL;
1662     GNUNET_break (0);
1663     return GNUNET_SYSERR;
1664   }
1665   s->plugin->cur_requests++;
1666   LOG (GNUNET_ERROR_TYPE_INFO,
1667        "GET request `%s' established, number of requests increased to %u\n",
1668        s->url,
1669        s->plugin->cur_requests);
1670   return GNUNET_OK;
1671 }
1672
1673
1674 /**
1675  * Connect a HTTP put request
1676  *
1677  * @param s the session to connect
1678  * @return #GNUNET_SYSERR for hard failure, #GNUNET_OK for ok
1679  */
1680 static int
1681 client_connect_put (struct GNUNET_ATS_Session *s)
1682 {
1683   CURLMcode mret;
1684   struct HttpAddress *ha;
1685   uint32_t options;
1686
1687   ha = (struct HttpAddress *) s->address->address;
1688   options = ntohl (ha->options);
1689   /* create put request */
1690   LOG (GNUNET_ERROR_TYPE_DEBUG,
1691        "Session %p: Init PUT handle\n",
1692        s);
1693   s->put.easyhandle = curl_easy_init ();
1694   s->put.s = s;
1695 #if VERBOSE_CURL
1696   curl_easy_setopt (s->put.easyhandle,
1697                     CURLOPT_VERBOSE,
1698                     1L);
1699   curl_easy_setopt (s->put.easyhandle,
1700                     CURLOPT_DEBUGFUNCTION,
1701                     &client_log);
1702   curl_easy_setopt (s->put.easyhandle,
1703                     CURLOPT_DEBUGDATA,
1704                     &s->put);
1705 #endif
1706   if (0 != (options & HTTP_OPTIONS_TCP_STEALTH))
1707   {
1708 #ifdef TCP_STEALTH
1709     curl_easy_setopt (s->put.easyhandle,
1710                       CURLOPT_OPENSOCKETFUNCTION,
1711                       &open_tcp_stealth_socket_cb);
1712     curl_easy_setopt (s->put.easyhandle,
1713                       CURLOPT_OPENSOCKETDATA,
1714                       s);
1715 #else
1716     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1717                 "Cannot connect, TCP STEALTH needed and not supported by kernel.\n");
1718     curl_easy_cleanup (s->put.easyhandle);
1719     s->put.easyhandle = NULL;
1720     s->put.s = NULL;
1721     s->put.state = H_DISCONNECTED;
1722     return GNUNET_SYSERR;
1723 #endif
1724   }
1725 #if BUILD_HTTPS
1726   curl_easy_setopt (s->put.easyhandle,
1727                     CURLOPT_SSLVERSION,
1728                     CURL_SSLVERSION_TLSv1);
1729   {
1730     struct HttpAddress *ha;
1731     ha = (struct HttpAddress *) s->address->address;
1732
1733     if (HTTP_OPTIONS_VERIFY_CERTIFICATE ==
1734         (ntohl (ha->options) & HTTP_OPTIONS_VERIFY_CERTIFICATE))
1735     {
1736       curl_easy_setopt (s->put.easyhandle,
1737                         CURLOPT_SSL_VERIFYPEER,
1738                         1L);
1739       curl_easy_setopt (s->put.easyhandle,
1740                         CURLOPT_SSL_VERIFYHOST,
1741                         2L);
1742     }
1743     else
1744     {
1745       curl_easy_setopt (s->put.easyhandle,
1746                         CURLOPT_SSL_VERIFYPEER,
1747                         0L);
1748       curl_easy_setopt (s->put.easyhandle,
1749                         CURLOPT_SSL_VERIFYHOST,
1750                         0L);
1751     }
1752   }
1753   curl_easy_setopt (s->put.easyhandle,
1754                     CURLOPT_PROTOCOLS,
1755                     CURLPROTO_HTTPS);
1756   curl_easy_setopt (s->put.easyhandle,
1757                     CURLOPT_REDIR_PROTOCOLS,
1758                     CURLPROTO_HTTPS);
1759 #else
1760   curl_easy_setopt (s->put.easyhandle,
1761                     CURLOPT_PROTOCOLS,
1762                     CURLPROTO_HTTP);
1763   curl_easy_setopt (s->put.easyhandle,
1764                     CURLOPT_REDIR_PROTOCOLS,
1765                     CURLPROTO_HTTP);
1766 #endif
1767   if (NULL != s->plugin->proxy_hostname)
1768   {
1769     curl_easy_setopt (s->put.easyhandle,
1770                       CURLOPT_PROXY,
1771                       s->plugin->proxy_hostname);
1772     curl_easy_setopt (s->put.easyhandle,
1773                       CURLOPT_PROXYTYPE,
1774                       s->plugin->proxytype);
1775     if (NULL != s->plugin->proxy_username)
1776       curl_easy_setopt (s->put.easyhandle,
1777                         CURLOPT_PROXYUSERNAME,
1778                         s->plugin->proxy_username);
1779     if (NULL != s->plugin->proxy_password)
1780       curl_easy_setopt (s->put.easyhandle,
1781                         CURLOPT_PROXYPASSWORD,
1782                         s->plugin->proxy_password);
1783     if (GNUNET_YES == s->plugin->proxy_use_httpproxytunnel)
1784       curl_easy_setopt (s->put.easyhandle,
1785                         CURLOPT_HTTPPROXYTUNNEL,
1786                         s->plugin->proxy_use_httpproxytunnel);
1787   }
1788
1789   curl_easy_setopt (s->put.easyhandle,
1790                     CURLOPT_URL,
1791                     s->url);
1792   curl_easy_setopt (s->put.easyhandle,
1793                     CURLOPT_UPLOAD,
1794                     1L);
1795   curl_easy_setopt (s->put.easyhandle,
1796                     CURLOPT_READFUNCTION,
1797                     &client_send_cb);
1798   curl_easy_setopt (s->put.easyhandle,
1799                     CURLOPT_READDATA,
1800                     s);
1801   curl_easy_setopt (s->put.easyhandle,
1802                     CURLOPT_WRITEFUNCTION,
1803                     &client_receive_put);
1804   curl_easy_setopt (s->put.easyhandle,
1805                     CURLOPT_WRITEDATA,
1806                     s);
1807   /* No timeout by default, timeout done with session timeout */
1808   curl_easy_setopt (s->put.easyhandle,
1809                     CURLOPT_TIMEOUT,
1810                     0L);
1811   curl_easy_setopt (s->put.easyhandle,
1812                     CURLOPT_PRIVATE,
1813                     s);
1814   curl_easy_setopt (s->put.easyhandle,
1815                     CURLOPT_CONNECTTIMEOUT_MS,
1816                     (long) (HTTP_CLIENT_NOT_VALIDATED_TIMEOUT.rel_value_us / 1000LL));
1817   curl_easy_setopt (s->put.easyhandle, CURLOPT_BUFFERSIZE,
1818                     2 * GNUNET_MAX_MESSAGE_SIZE);
1819 #if CURL_TCP_NODELAY
1820   curl_easy_setopt (s->put.easyhandle, CURLOPT_TCP_NODELAY, 1);
1821 #endif
1822   mret = curl_multi_add_handle (s->plugin->curl_multi_handle,
1823                                 s->put.easyhandle);
1824   if (CURLM_OK != mret)
1825   {
1826     LOG (GNUNET_ERROR_TYPE_ERROR,
1827          "Session %p : Failed to add PUT handle to multihandle: `%s'\n",
1828          s, curl_multi_strerror (mret));
1829     curl_easy_cleanup (s->put.easyhandle);
1830     s->put.easyhandle = NULL;
1831     s->put.s = NULL;
1832     s->put.state = H_DISCONNECTED;
1833     return GNUNET_SYSERR;
1834   }
1835   s->put.state = H_CONNECTED;
1836   s->plugin->cur_requests++;
1837
1838   LOG  (GNUNET_ERROR_TYPE_INFO,
1839       "PUT request `%s' established, number of requests increased to %u\n",
1840       s->url, s->plugin->cur_requests);
1841
1842   return GNUNET_OK;
1843 }
1844
1845
1846 /**
1847  * Connect both PUT and GET request for a session
1848  *
1849  * @param s the session to connect
1850  * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
1851  */
1852 static int
1853 client_connect (struct GNUNET_ATS_Session *s)
1854 {
1855   struct HTTP_Client_Plugin *plugin = s->plugin;
1856   int res = GNUNET_OK;
1857
1858   /* create url */
1859   if (NULL ==
1860       http_common_plugin_address_to_string(plugin->protocol,
1861                                            s->address->address,
1862                                            s->address->address_length))
1863   {
1864     LOG (GNUNET_ERROR_TYPE_DEBUG,
1865          "Invalid address peer `%s'\n",
1866          GNUNET_i2s(&s->address->peer));
1867     return GNUNET_SYSERR;
1868   }
1869
1870   GNUNET_asprintf (&s->url,
1871                    "%s/%s;%u",
1872                    http_common_plugin_address_to_url (NULL,
1873                                                       s->address->address,
1874                                                       s->address->address_length),
1875                    GNUNET_i2s_full (plugin->env->my_identity),
1876                    plugin->last_tag);
1877
1878   plugin->last_tag++;
1879   LOG (GNUNET_ERROR_TYPE_DEBUG,
1880        "Initiating outbound session peer `%s' using address `%s'\n",
1881        GNUNET_i2s (&s->address->peer), s->url);
1882
1883   if (GNUNET_SYSERR == client_connect_get (s))
1884     return GNUNET_SYSERR;
1885   /* If we are emulating an XHR client then delay sending a PUT request until
1886    * there is something to send.
1887    */
1888   if (GNUNET_YES == plugin->emulate_xhr)
1889   {
1890     s->put.state = H_TMP_DISCONNECTED;
1891   }
1892   else if (GNUNET_SYSERR == client_connect_put (s))
1893     return GNUNET_SYSERR;
1894
1895   LOG (GNUNET_ERROR_TYPE_DEBUG,
1896        "Session %p: connected with GET %p and PUT %p\n",
1897        s, s->get.easyhandle,
1898        s->put.easyhandle);
1899   /* Perform connect */
1900   GNUNET_STATISTICS_set (plugin->env->stats,
1901                          HTTP_STAT_STR_CONNECTIONS,
1902                          plugin->cur_requests,
1903                          GNUNET_NO);
1904   /* Re-schedule since handles have changed */
1905   if (NULL != plugin->client_perform_task)
1906   {
1907     GNUNET_SCHEDULER_cancel (plugin->client_perform_task);
1908     plugin->client_perform_task = NULL;
1909   }
1910
1911   /* Schedule task to run immediately */
1912   plugin->client_perform_task = GNUNET_SCHEDULER_add_now (client_run,
1913                                                           plugin);
1914   return res;
1915 }
1916
1917
1918 /**
1919  * Function obtain the network type for a session
1920  *
1921  * @param cls closure (`struct Plugin*`)
1922  * @param session the session
1923  * @return the network type
1924  */
1925 static enum GNUNET_ATS_Network_Type
1926 http_client_plugin_get_network (void *cls,
1927                                 struct GNUNET_ATS_Session *session)
1928 {
1929   return session->scope;
1930 }
1931
1932
1933 /**
1934  * Function obtain the network type for an address.
1935  *
1936  * @param cls closure (`struct Plugin *`)
1937  * @param address the address
1938  * @return the network type
1939  */
1940 static enum GNUNET_ATS_Network_Type
1941 http_client_plugin_get_network_for_address (void *cls,
1942                                             const struct GNUNET_HELLO_Address *address)
1943 {
1944   struct HTTP_Client_Plugin *plugin = cls;
1945
1946   return http_common_get_network_for_address (plugin->env,
1947                                               address);
1948 }
1949
1950
1951 /**
1952  * Session was idle, so disconnect it
1953  *
1954  * @param cls the `struct GNUNET_ATS_Session` of the idle session
1955  */
1956 static void
1957 client_session_timeout (void *cls)
1958 {
1959   struct GNUNET_ATS_Session *s = cls;
1960   struct GNUNET_TIME_Relative left;
1961
1962   s->timeout_task = NULL;
1963   left = GNUNET_TIME_absolute_get_remaining (s->timeout);
1964   if (0 != left.rel_value_us)
1965   {
1966     /* not actually our turn yet, but let's at least update
1967        the monitor, it may think we're about to die ... */
1968     notify_session_monitor (s->plugin,
1969                             s,
1970                             GNUNET_TRANSPORT_SS_UPDATE);
1971     s->timeout_task = GNUNET_SCHEDULER_add_delayed (left,
1972                                                     &client_session_timeout,
1973                                                     s);
1974     return;
1975   }
1976   LOG (TIMEOUT_LOG,
1977        "Session %p was idle for %s, disconnecting\n",
1978        s,
1979        GNUNET_STRINGS_relative_time_to_string (HTTP_CLIENT_SESSION_TIMEOUT,
1980                                                GNUNET_YES));
1981   GNUNET_assert (GNUNET_OK ==
1982                  http_client_plugin_session_disconnect (s->plugin,
1983                                                  s));
1984 }
1985
1986
1987 /**
1988  * Creates a new outbound session the transport service will use to
1989  * send data to the peer
1990  *
1991  * @param cls the plugin
1992  * @param address the address
1993  * @return the session or NULL of max connections exceeded
1994  */
1995 static struct GNUNET_ATS_Session *
1996 http_client_plugin_get_session (void *cls,
1997                                 const struct GNUNET_HELLO_Address *address)
1998 {
1999   struct HTTP_Client_Plugin *plugin = cls;
2000   struct GNUNET_ATS_Session *s;
2001   struct sockaddr *sa;
2002   enum GNUNET_ATS_Network_Type net_type;
2003   size_t salen = 0;
2004   int res;
2005
2006   GNUNET_assert (NULL != address->address);
2007
2008   /* find existing session */
2009   s = client_lookup_session (plugin, address);
2010   if (NULL != s)
2011     return s;
2012
2013   /* create a new session */
2014   if (plugin->max_requests <= plugin->cur_requests)
2015   {
2016     LOG (GNUNET_ERROR_TYPE_WARNING,
2017          "Maximum number of requests (%u) reached: "
2018          "cannot connect to peer `%s'\n",
2019          plugin->max_requests,
2020          GNUNET_i2s (&address->peer));
2021     return NULL;
2022   }
2023
2024   /* Determine network location */
2025   net_type = GNUNET_ATS_NET_UNSPECIFIED;
2026   sa = http_common_socket_from_address (address->address,
2027                                         address->address_length,
2028                                         &res);
2029   if (GNUNET_SYSERR == res)
2030     return NULL;
2031   if (GNUNET_YES == res)
2032   {
2033     GNUNET_assert (NULL != sa);
2034     if (AF_INET == sa->sa_family)
2035     {
2036       salen = sizeof (struct sockaddr_in);
2037     }
2038     else if (AF_INET6 == sa->sa_family)
2039     {
2040       salen = sizeof (struct sockaddr_in6);
2041     }
2042     net_type = plugin->env->get_address_type (plugin->env->cls, sa, salen);
2043     GNUNET_free (sa);
2044   }
2045   else if (GNUNET_NO == res)
2046   {
2047     /* Cannot convert to sockaddr -> is external hostname */
2048     net_type = GNUNET_ATS_NET_WAN;
2049   }
2050   if (GNUNET_ATS_NET_UNSPECIFIED == net_type)
2051   {
2052     GNUNET_break (0);
2053     return NULL;
2054   }
2055
2056   s = GNUNET_new (struct GNUNET_ATS_Session);
2057   s->plugin = plugin;
2058   s->address = GNUNET_HELLO_address_copy (address);
2059   s->scope = net_type;
2060
2061   s->put.state = H_NOT_CONNECTED;
2062   s->timeout = GNUNET_TIME_relative_to_absolute (HTTP_CLIENT_SESSION_TIMEOUT);
2063   s->timeout_task =  GNUNET_SCHEDULER_add_delayed (HTTP_CLIENT_SESSION_TIMEOUT,
2064                                                    &client_session_timeout,
2065                                                    s);
2066   LOG (GNUNET_ERROR_TYPE_DEBUG,
2067        "Created new session %p for `%s' address `%s''\n",
2068        s,
2069        http_common_plugin_address_to_string (plugin->protocol,
2070                                              s->address->address,
2071                                              s->address->address_length),
2072        GNUNET_i2s (&s->address->peer));
2073
2074   /* add new session */
2075   (void) GNUNET_CONTAINER_multipeermap_put (plugin->sessions,
2076                                             &s->address->peer,
2077                                             s,
2078                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2079   /* initiate new connection */
2080   if (GNUNET_SYSERR == client_connect (s))
2081   {
2082     LOG (GNUNET_ERROR_TYPE_ERROR,
2083          "Cannot connect to peer `%s' address `%s''\n",
2084          http_common_plugin_address_to_string (plugin->protocol,
2085              s->address->address, s->address->address_length),
2086              GNUNET_i2s (&s->address->peer));
2087     client_delete_session (s);
2088     return NULL;
2089   }
2090   notify_session_monitor (plugin,
2091                           s,
2092                           GNUNET_TRANSPORT_SS_INIT);
2093   notify_session_monitor (plugin,
2094                           s,
2095                           GNUNET_TRANSPORT_SS_UP); /* or handshake? */
2096   return s;
2097 }
2098
2099
2100 /**
2101  * Setup http_client plugin
2102  *
2103  * @param plugin the plugin handle
2104  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
2105  */
2106 static int
2107 client_start (struct HTTP_Client_Plugin *plugin)
2108 {
2109   curl_global_init (CURL_GLOBAL_ALL);
2110   plugin->curl_multi_handle = curl_multi_init ();
2111
2112   if (NULL == plugin->curl_multi_handle)
2113   {
2114     LOG (GNUNET_ERROR_TYPE_ERROR,
2115          _("Could not initialize curl multi handle, failed to start %s plugin!\n"),
2116          plugin->name);
2117     return GNUNET_SYSERR;
2118   }
2119   return GNUNET_OK;
2120 }
2121
2122
2123 /**
2124  * Another peer has suggested an address for this
2125  * peer and transport plugin.  Check that this could be a valid
2126  * address.  If so, consider adding it to the list
2127  * of addresses.
2128  *
2129  * @param cls closure with the `struct Plugin`
2130  * @param addr pointer to the address
2131  * @param addrlen length of @a addr
2132  * @return #GNUNET_OK if this is a plausible address for this peer
2133  *         and transport; always returns #GNUNET_NO (this is the client!)
2134  */
2135 static int
2136 http_client_plugin_address_suggested (void *cls,
2137                                       const void *addr,
2138                                       size_t addrlen)
2139 {
2140   /* A HTTP/S client does not have any valid address so:*/
2141   return GNUNET_NO;
2142 }
2143
2144
2145 /**
2146  * Exit point from the plugin.
2147  *
2148  * @param cls api as closure
2149  * @return NULL
2150  */
2151 void *
2152 LIBGNUNET_PLUGIN_TRANSPORT_DONE (void *cls)
2153 {
2154   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2155   struct HTTP_Client_Plugin *plugin = api->cls;
2156
2157   if (NULL == api->cls)
2158   {
2159     /* Stub shutdown */
2160     GNUNET_free (api);
2161     return NULL;
2162   }
2163   LOG (GNUNET_ERROR_TYPE_DEBUG,
2164        _("Shutting down plugin `%s'\n"),
2165        plugin->name);
2166   GNUNET_CONTAINER_multipeermap_iterate (plugin->sessions,
2167                                          &destroy_session_cb,
2168                                          plugin);
2169   if (NULL != plugin->client_perform_task)
2170   {
2171     GNUNET_SCHEDULER_cancel (plugin->client_perform_task);
2172     plugin->client_perform_task = NULL;
2173   }
2174   if (NULL != plugin->curl_multi_handle)
2175   {
2176     curl_multi_cleanup (plugin->curl_multi_handle);
2177     plugin->curl_multi_handle = NULL;
2178   }
2179   curl_global_cleanup ();
2180   LOG (GNUNET_ERROR_TYPE_DEBUG,
2181        _("Shutdown for plugin `%s' complete\n"),
2182        plugin->name);
2183   GNUNET_CONTAINER_multipeermap_destroy (plugin->sessions);
2184   GNUNET_free_non_null (plugin->proxy_hostname);
2185   GNUNET_free_non_null (plugin->proxy_username);
2186   GNUNET_free_non_null (plugin->proxy_password);
2187   GNUNET_free (plugin);
2188   GNUNET_free (api);
2189   return NULL;
2190 }
2191
2192
2193 /**
2194  * Configure plugin
2195  *
2196  * @param plugin the plugin handle
2197  * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
2198  */
2199 static int
2200 client_configure_plugin (struct HTTP_Client_Plugin *plugin)
2201 {
2202   unsigned long long max_requests;
2203   char *proxy_type;
2204
2205   /* Optional parameters */
2206   if (GNUNET_OK !=
2207       GNUNET_CONFIGURATION_get_value_number (plugin->env->cfg,
2208                                              plugin->name,
2209                                              "MAX_CONNECTIONS",
2210                                              &max_requests))
2211     max_requests = 128;
2212   plugin->max_requests = max_requests;
2213
2214   LOG (GNUNET_ERROR_TYPE_DEBUG,
2215        _("Maximum number of requests is %u\n"),
2216        plugin->max_requests);
2217
2218   /* Read proxy configuration */
2219   if (GNUNET_OK ==
2220       GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
2221                                              plugin->name,
2222                                              "PROXY",
2223                                              &plugin->proxy_hostname))
2224   {
2225     LOG (GNUNET_ERROR_TYPE_DEBUG,
2226          "Found proxy host: `%s'\n",
2227          plugin->proxy_hostname);
2228     /* proxy username */
2229     if (GNUNET_OK ==
2230         GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
2231                                                plugin->name,
2232                                                "PROXY_USERNAME",
2233                                                &plugin->proxy_username))
2234     {
2235       LOG (GNUNET_ERROR_TYPE_DEBUG,
2236            "Found proxy username name: `%s'\n",
2237            plugin->proxy_username);
2238     }
2239
2240     /* proxy password */
2241     if (GNUNET_OK ==
2242         GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
2243                                                plugin->name,
2244                                                "PROXY_PASSWORD",
2245                                                &plugin->proxy_password))
2246     {
2247       LOG (GNUNET_ERROR_TYPE_DEBUG,
2248            "Found proxy password name: `%s'\n",
2249            plugin->proxy_password);
2250     }
2251
2252     /* proxy type */
2253     if (GNUNET_OK ==
2254         GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
2255                                                plugin->name,
2256                                                "PROXY_TYPE",
2257                                                &proxy_type))
2258     {
2259       GNUNET_STRINGS_utf8_toupper (proxy_type, proxy_type);
2260
2261       if (0 == strcmp(proxy_type, "HTTP"))
2262         plugin->proxytype = CURLPROXY_HTTP;
2263       else if (0 == strcmp(proxy_type, "SOCKS4"))
2264         plugin->proxytype = CURLPROXY_SOCKS4;
2265       else if (0 == strcmp(proxy_type, "SOCKS5"))
2266         plugin->proxytype = CURLPROXY_SOCKS5;
2267       else if (0 == strcmp(proxy_type, "SOCKS4A"))
2268         plugin->proxytype = CURLPROXY_SOCKS4A;
2269       else if (0 == strcmp(proxy_type, "SOCKS5_HOSTNAME "))
2270         plugin->proxytype = CURLPROXY_SOCKS5_HOSTNAME ;
2271       else
2272       {
2273         LOG (GNUNET_ERROR_TYPE_ERROR,
2274              _("Invalid proxy type: `%s', disabling proxy! Check configuration!\n"),
2275              proxy_type);
2276
2277         GNUNET_free (proxy_type);
2278         GNUNET_free (plugin->proxy_hostname);
2279         plugin->proxy_hostname = NULL;
2280         GNUNET_free_non_null (plugin->proxy_username);
2281         plugin->proxy_username = NULL;
2282         GNUNET_free_non_null (plugin->proxy_password);
2283         plugin->proxy_password = NULL;
2284
2285         return GNUNET_SYSERR;
2286       }
2287
2288       LOG (GNUNET_ERROR_TYPE_DEBUG,
2289            "Found proxy type: `%s'\n",
2290            proxy_type);
2291     }
2292
2293     /* proxy http tunneling */
2294     plugin->proxy_use_httpproxytunnel
2295       = GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg,
2296                                               plugin->name,
2297                                               "PROXY_HTTP_TUNNELING");
2298     if (GNUNET_SYSERR == plugin->proxy_use_httpproxytunnel)
2299       plugin->proxy_use_httpproxytunnel = GNUNET_NO;
2300
2301     GNUNET_free_non_null (proxy_type);
2302   }
2303
2304   /* Should we emulate an XHR client for testing? */
2305   plugin->emulate_xhr
2306     = GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg,
2307                                             plugin->name,
2308                                             "EMULATE_XHR");
2309   return GNUNET_OK;
2310 }
2311
2312
2313 /**
2314  * Function to convert an address to a human-readable string.
2315  *
2316  * @param cls closure
2317  * @param addr address to convert
2318  * @param addrlen address length
2319  * @return res string if conversion was successful, NULL otherwise
2320  */
2321 static const char *
2322 http_client_plugin_address_to_string (void *cls,
2323                                       const void *addr,
2324                                       size_t addrlen)
2325 {
2326   return http_common_plugin_address_to_string (PLUGIN_NAME,
2327                                                addr,
2328                                                addrlen);
2329 }
2330
2331
2332 /**
2333  * Function that will be called whenever the transport service wants to
2334  * notify the plugin that a session is still active and in use and
2335  * therefore the session timeout for this session has to be updated
2336  *
2337  * @param cls closure
2338  * @param peer which peer was the session for
2339  * @param session which session is being updated
2340  */
2341 static void
2342 http_client_plugin_update_session_timeout (void *cls,
2343                                            const struct GNUNET_PeerIdentity *peer,
2344                                            struct GNUNET_ATS_Session *session)
2345 {
2346   client_reschedule_session_timeout (session);
2347 }
2348
2349
2350 /**
2351  * Function that will be called whenever the transport service wants to
2352  * notify the plugin that the inbound quota changed and that the plugin
2353  * should update it's delay for the next receive value
2354  *
2355  * @param cls closure
2356  * @param peer which peer was the session for
2357  * @param s which session is being updated
2358  * @param delay new delay to use for receiving
2359  */
2360 static void
2361 http_client_plugin_update_inbound_delay (void *cls,
2362                                          const struct GNUNET_PeerIdentity *peer,
2363                                          struct GNUNET_ATS_Session *s,
2364                                          struct GNUNET_TIME_Relative delay)
2365 {
2366   s->next_receive = GNUNET_TIME_relative_to_absolute (delay);
2367   LOG (GNUNET_ERROR_TYPE_DEBUG,
2368        "New inbound delay %s\n",
2369        GNUNET_STRINGS_relative_time_to_string (delay,
2370                                                GNUNET_NO));
2371   if (s->recv_wakeup_task != NULL)
2372   {
2373     GNUNET_SCHEDULER_cancel (s->recv_wakeup_task);
2374     s->recv_wakeup_task
2375       = GNUNET_SCHEDULER_add_delayed (delay,
2376                                       &client_wake_up,
2377                                       s);
2378   }
2379 }
2380
2381
2382 /**
2383  * Return information about the given session to the
2384  * monitor callback.
2385  *
2386  * @param cls the `struct Plugin` with the monitor callback (`sic`)
2387  * @param peer peer we send information about
2388  * @param value our `struct GNUNET_ATS_Session` to send information about
2389  * @return #GNUNET_OK (continue to iterate)
2390  */
2391 static int
2392 send_session_info_iter (void *cls,
2393                         const struct GNUNET_PeerIdentity *peer,
2394                         void *value)
2395 {
2396   struct HTTP_Client_Plugin *plugin = cls;
2397   struct GNUNET_ATS_Session *session = value;
2398
2399   notify_session_monitor (plugin,
2400                           session,
2401                           GNUNET_TRANSPORT_SS_INIT);
2402   notify_session_monitor (plugin,
2403                           session,
2404                           GNUNET_TRANSPORT_SS_UP); /* FIXME: or handshake? */
2405   return GNUNET_OK;
2406 }
2407
2408
2409 /**
2410  * Begin monitoring sessions of a plugin.  There can only
2411  * be one active monitor per plugin (i.e. if there are
2412  * multiple monitors, the transport service needs to
2413  * multiplex the generated events over all of them).
2414  *
2415  * @param cls closure of the plugin
2416  * @param sic callback to invoke, NULL to disable monitor;
2417  *            plugin will being by iterating over all active
2418  *            sessions immediately and then enter monitor mode
2419  * @param sic_cls closure for @a sic
2420  */
2421 static void
2422 http_client_plugin_setup_monitor (void *cls,
2423                                   GNUNET_TRANSPORT_SessionInfoCallback sic,
2424                                   void *sic_cls)
2425 {
2426   struct HTTP_Client_Plugin *plugin = cls;
2427
2428   plugin->sic = sic;
2429   plugin->sic_cls = sic_cls;
2430   if (NULL != sic)
2431   {
2432     GNUNET_CONTAINER_multipeermap_iterate (plugin->sessions,
2433                                            &send_session_info_iter,
2434                                            plugin);
2435     /* signal end of first iteration */
2436     sic (sic_cls, NULL, NULL);
2437   }
2438 }
2439
2440
2441 /**
2442  * Entry point for the plugin.
2443  */
2444 void *
2445 LIBGNUNET_PLUGIN_TRANSPORT_INIT (void *cls)
2446 {
2447   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2448   struct GNUNET_TRANSPORT_PluginFunctions *api;
2449   struct HTTP_Client_Plugin *plugin;
2450
2451   if (NULL == env->receive)
2452   {
2453     /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
2454        initialze the plugin or the API */
2455     api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
2456     api->cls = NULL;
2457     api->address_to_string = &http_client_plugin_address_to_string;
2458     api->string_to_address = &http_common_plugin_string_to_address;
2459     api->address_pretty_printer = &http_common_plugin_address_pretty_printer;
2460     return api;
2461   }
2462
2463   plugin = GNUNET_new (struct HTTP_Client_Plugin);
2464   plugin->env = env;
2465   plugin->sessions = GNUNET_CONTAINER_multipeermap_create (128,
2466                                                            GNUNET_YES);
2467   api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
2468   api->cls = plugin;
2469   api->send = &http_client_plugin_send;
2470   api->disconnect_session = &http_client_plugin_session_disconnect;
2471   api->query_keepalive_factor = &http_client_query_keepalive_factor;
2472   api->disconnect_peer = &http_client_plugin_peer_disconnect;
2473   api->check_address = &http_client_plugin_address_suggested;
2474   api->get_session = &http_client_plugin_get_session;
2475   api->address_to_string = &http_client_plugin_address_to_string;
2476   api->string_to_address = &http_common_plugin_string_to_address;
2477   api->address_pretty_printer = &http_common_plugin_address_pretty_printer;
2478   api->get_network = &http_client_plugin_get_network;
2479   api->get_network_for_address = &http_client_plugin_get_network_for_address;
2480   api->update_session_timeout = &http_client_plugin_update_session_timeout;
2481   api->update_inbound_delay = &http_client_plugin_update_inbound_delay;
2482   api->setup_monitor = &http_client_plugin_setup_monitor;
2483 #if BUILD_HTTPS
2484   plugin->name = "transport-https_client";
2485   plugin->protocol = "https";
2486 #else
2487   plugin->name = "transport-http_client";
2488   plugin->protocol = "http";
2489 #endif
2490   plugin->last_tag = 1;
2491
2492   if (GNUNET_SYSERR == client_configure_plugin (plugin))
2493   {
2494     LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
2495     return NULL;
2496   }
2497
2498   /* Start client */
2499   if (GNUNET_SYSERR == client_start (plugin))
2500   {
2501     LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
2502     return NULL;
2503   }
2504   return api;
2505 }
2506
2507 /* end of plugin_transport_http_client.c */