2b0b8939e8614f9b0284522d98ed34cd0b5f1e40
[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_SERVER_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_SERVER_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   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   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 = GNUNET_SCHEDULER_add_delayed (PUT_DISCONNECT_TIMEOUT,
1065         &client_put_disconnect, s);
1066     s->put.state = H_PAUSED;
1067     return CURL_READFUNC_PAUSE;
1068   }
1069   /* data to send */
1070   GNUNET_assert (msg->pos < msg->size);
1071   /* calculate how much fits in buffer */
1072   len = GNUNET_MIN (msg->size - msg->pos,
1073                     size * nmemb);
1074   memcpy (stream, &msg->buf[msg->pos], len);
1075   msg->pos += len;
1076   if (msg->pos == msg->size)
1077   {
1078     LOG (GNUNET_ERROR_TYPE_DEBUG,
1079          "Session %p/request %p: sent message with %u bytes sent, removing message from queue\n",
1080          s,
1081          s->put.easyhandle,
1082          msg->size,
1083          msg->pos);
1084     /* Calling transmit continuation  */
1085     GNUNET_CONTAINER_DLL_remove (s->msg_head,
1086                                  s->msg_tail,
1087                                  msg);
1088     GNUNET_assert (0 < s->msgs_in_queue);
1089     s->msgs_in_queue--;
1090     GNUNET_assert (msg->size <= s->bytes_in_queue);
1091     s->bytes_in_queue -= msg->size;
1092     if (NULL != msg->transmit_cont)
1093       msg->transmit_cont (msg->transmit_cont_cls,
1094                           &s->address->peer,
1095                           GNUNET_OK,
1096                           msg->size,
1097                           msg->size + s->overhead);
1098     s->overhead = 0;
1099     GNUNET_free (msg);
1100   }
1101   notify_session_monitor (plugin,
1102                           s,
1103                           GNUNET_TRANSPORT_SS_UPDATE);
1104   GNUNET_asprintf (&stat_txt,
1105                    "# bytes currently in %s_client buffers",
1106                    plugin->protocol);
1107   GNUNET_STATISTICS_update (plugin->env->stats,
1108                             stat_txt,
1109                             - len,
1110                             GNUNET_NO);
1111   GNUNET_free (stat_txt);
1112   GNUNET_asprintf (&stat_txt,
1113                    "# bytes transmitted via %s_client",
1114                    plugin->protocol);
1115   GNUNET_STATISTICS_update (plugin->env->stats,
1116                             stat_txt,
1117                             len,
1118                             GNUNET_NO);
1119   GNUNET_free (stat_txt);
1120   return len;
1121 }
1122
1123
1124 /**
1125  * Wake up a curl handle which was suspended
1126  *
1127  * @param cls the session
1128  */
1129 static void
1130 client_wake_up (void *cls)
1131 {
1132   struct GNUNET_ATS_Session *s = cls;
1133   const struct GNUNET_SCHEDULER_TaskContext *tc;
1134
1135   s->recv_wakeup_task = NULL;
1136   tc = GNUNET_SCHEDULER_get_task_context ();
1137   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1138     return;
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 client not used
1162  * @param message the message received
1163  * @return always #GNUNET_OK
1164  */
1165 static int
1166 client_receive_mst_cb (void *cls,
1167                        void *client,
1168                        const struct GNUNET_MessageHeader *message)
1169 {
1170   struct GNUNET_ATS_Session *s = cls;
1171   struct HTTP_Client_Plugin *plugin;
1172   struct GNUNET_TIME_Relative delay;
1173   char *stat_txt;
1174
1175   plugin = s->plugin;
1176   delay = s->plugin->env->receive (plugin->env->cls,
1177                                    s->address,
1178                                    s,
1179                                    message);
1180   GNUNET_asprintf (&stat_txt,
1181                    "# bytes received via %s_client",
1182                    plugin->protocol);
1183   GNUNET_STATISTICS_update (plugin->env->stats,
1184                             stat_txt,
1185                             ntohs (message->size),
1186                             GNUNET_NO);
1187   GNUNET_free (stat_txt);
1188
1189   s->next_receive = GNUNET_TIME_relative_to_absolute (delay);
1190   if (GNUNET_TIME_absolute_get ().abs_value_us < s->next_receive.abs_value_us)
1191   {
1192     LOG (GNUNET_ERROR_TYPE_DEBUG,
1193          "Client: peer `%s' address `%s' next read delayed for %s\n",
1194          GNUNET_i2s (&s->address->peer),
1195          http_common_plugin_address_to_string (s->plugin->protocol,
1196                                                s->address->address,
1197                                                s->address->address_length),
1198          GNUNET_STRINGS_relative_time_to_string (delay,
1199                                                  GNUNET_YES));
1200   }
1201   client_reschedule_session_timeout (s);
1202   return GNUNET_OK;
1203 }
1204
1205
1206 /**
1207  * Callback method used with libcurl when data for a PUT request are
1208  * received.  We do not expect data here, so we just discard it.
1209  *
1210  * @param stream pointer where to write data
1211  * @param size size of an individual element
1212  * @param nmemb count of elements that can be written to the buffer
1213  * @param cls destination pointer, passed to the libcurl handle
1214  * @return bytes read from stream
1215  */
1216 static size_t
1217 client_receive_put (void *stream,
1218                     size_t size,
1219                     size_t nmemb,
1220                     void *cls)
1221 {
1222   return size * nmemb;
1223 }
1224
1225
1226 /**
1227  * Callback method used with libcurl when data for a GET request are
1228  * received. Forward to MST
1229  *
1230  * @param stream pointer where to write data
1231  * @param size size of an individual element
1232  * @param nmemb count of elements that can be written to the buffer
1233  * @param cls destination pointer, passed to the libcurl handle
1234  * @return bytes read from stream
1235  */
1236 static size_t
1237 client_receive (void *stream,
1238                 size_t size,
1239                 size_t nmemb,
1240                 void *cls)
1241 {
1242   struct GNUNET_ATS_Session *s = cls;
1243   struct GNUNET_TIME_Absolute now;
1244   size_t len = size * nmemb;
1245
1246   LOG (GNUNET_ERROR_TYPE_DEBUG,
1247        "Session %p / request %p: Received %u bytes from peer `%s'\n",
1248        s,
1249        s->get.easyhandle,
1250        len,
1251        GNUNET_i2s (&s->address->peer));
1252   now = GNUNET_TIME_absolute_get ();
1253   if (now.abs_value_us < s->next_receive.abs_value_us)
1254   {
1255     struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
1256     struct GNUNET_TIME_Relative delta
1257       = GNUNET_TIME_absolute_get_difference (now, s->next_receive);
1258
1259     LOG (GNUNET_ERROR_TYPE_DEBUG,
1260          "Session %p / request %p: No inbound bandwidth available! Next read was delayed for %s\n",
1261          s,
1262          s->get.easyhandle,
1263          GNUNET_STRINGS_relative_time_to_string (delta,
1264                                                  GNUNET_YES));
1265     if (s->recv_wakeup_task != NULL)
1266     {
1267       GNUNET_SCHEDULER_cancel (s->recv_wakeup_task);
1268       s->recv_wakeup_task = NULL;
1269     }
1270     s->recv_wakeup_task
1271       = GNUNET_SCHEDULER_add_delayed (delta,
1272                                       &client_wake_up,
1273                                       s);
1274     return CURL_WRITEFUNC_PAUSE;
1275   }
1276   if (NULL == s->msg_tk)
1277     s->msg_tk = GNUNET_SERVER_mst_create (&client_receive_mst_cb,
1278                                           s);
1279   GNUNET_SERVER_mst_receive (s->msg_tk,
1280                              s,
1281                              stream,
1282                              len,
1283                              GNUNET_NO,
1284                              GNUNET_NO);
1285   return len;
1286 }
1287
1288
1289 /**
1290  * Task performing curl operations
1291  *
1292  * @param cls plugin as closure
1293  */
1294 static void
1295 client_run (void *cls)
1296 {
1297   struct HTTP_Client_Plugin *plugin = cls;
1298   int running;
1299   long http_statuscode;
1300   CURLMcode mret;
1301   CURLMsg *msg;
1302   int put_request; /* GNUNET_YES if easy handle is put, GNUNET_NO for get */
1303   int msgs_left;
1304   const struct GNUNET_SCHEDULER_TaskContext *tc;
1305
1306   plugin->client_perform_task = NULL;
1307   tc = GNUNET_SCHEDULER_get_task_context ();
1308   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1309     return;
1310
1311   /* While data are available or timeouts occured */
1312   do
1313   {
1314     running = 0;
1315     /* Perform operations for all handles */
1316     mret = curl_multi_perform (plugin->curl_multi_handle, &running);
1317
1318     /* Get additional information for all handles */
1319     while (NULL != (msg = curl_multi_info_read (plugin->curl_multi_handle, &msgs_left)))
1320     {
1321       CURL *easy_h = msg->easy_handle;
1322       struct GNUNET_ATS_Session *s = NULL;
1323       char *d = NULL; /* curl requires 'd' to be a 'char *' */
1324
1325       GNUNET_assert (NULL != easy_h);
1326
1327       /* Obtain session from easy handle */
1328       GNUNET_assert (CURLE_OK == curl_easy_getinfo (easy_h, CURLINFO_PRIVATE, &d));
1329       s = (struct GNUNET_ATS_Session *) d;
1330       GNUNET_assert (NULL != s);
1331
1332       if (msg->msg != CURLMSG_DONE)
1333         continue; /* This should not happen */
1334
1335       /* Get HTTP response code */
1336       GNUNET_break (CURLE_OK == curl_easy_getinfo (easy_h,
1337           CURLINFO_RESPONSE_CODE, &http_statuscode));
1338
1339       if (easy_h == s->put.easyhandle)
1340         put_request = GNUNET_YES;
1341       else
1342         put_request = GNUNET_NO;
1343
1344       /* Log status of terminated request */
1345       if  ((0 != msg->data.result) || (http_statuscode != 200))
1346         LOG (GNUNET_ERROR_TYPE_DEBUG,
1347              "Session %p/request %p: %s request to `%s' ended with status %i reason %i: `%s'\n",
1348              s, msg->easy_handle,
1349              (GNUNET_YES == put_request) ? "PUT" : "GET",
1350              GNUNET_i2s (&s->address->peer),
1351              http_statuscode,
1352              msg->data.result,
1353              curl_easy_strerror (msg->data.result));
1354       else
1355         LOG (GNUNET_ERROR_TYPE_DEBUG,
1356              "Session %p/request %p: %s request to `%s' ended normal\n",
1357              s, msg->easy_handle,
1358              (GNUNET_YES == put_request) ? "PUT" : "GET",
1359              GNUNET_i2s (&s->address->peer));
1360
1361       /* Remove easy handle from multi handle */
1362       curl_multi_remove_handle (plugin->curl_multi_handle, easy_h);
1363
1364       /* Clean up easy handle */
1365       curl_easy_cleanup (easy_h);
1366
1367       /* Remove information */
1368       GNUNET_assert (plugin->cur_requests > 0);
1369       plugin->cur_requests--;
1370       LOG  (GNUNET_ERROR_TYPE_INFO,
1371           "%s request to %s done, number of requests decreased to %u\n",
1372           (GNUNET_YES == put_request) ? "PUT" : "GET",
1373           s->url,
1374           plugin->cur_requests);
1375
1376       if (GNUNET_YES == put_request)
1377       {
1378         /* Clean up a PUT request */
1379         s->put.easyhandle = NULL;
1380         s->put.s = NULL;
1381
1382         switch (s->put.state) {
1383           case H_NOT_CONNECTED:
1384           case H_DISCONNECTED:
1385           case H_TMP_DISCONNECTED:
1386             /* This must not happen */
1387             GNUNET_break (0);
1388             break;
1389           case H_TMP_RECONNECT_REQUIRED:
1390             /* Transport called send while disconnect in progess, reconnect */
1391             if (GNUNET_SYSERR == client_connect_put (s))
1392             {
1393               /* Reconnect failed, disconnect session */
1394               http_client_plugin_session_disconnect (plugin, s);
1395             }
1396             break;
1397           case H_TMP_DISCONNECTING:
1398             /* PUT gets temporarily disconnected */
1399             s->put.state = H_TMP_DISCONNECTED;
1400             break;
1401           case H_PAUSED:
1402           case H_CONNECTED:
1403             /* PUT gets permanently disconnected */
1404             s->put.state = H_DISCONNECTED;
1405             http_client_plugin_session_disconnect (plugin, s);
1406             break;
1407           default:
1408             GNUNET_break (0);
1409             break;
1410         }
1411       }
1412       else if (GNUNET_NO == put_request)
1413       {
1414         /* Clean up a GET request */
1415         s->get.easyhandle = NULL;
1416         s->get.s = NULL;
1417
1418         /* If we are emulating an XHR client we need to make another GET
1419          * request.
1420          */
1421         if (GNUNET_YES == plugin->emulate_xhr)
1422         {
1423           if (GNUNET_SYSERR == client_connect_get (s))
1424             http_client_plugin_session_disconnect (plugin, s);
1425         }
1426         else
1427         {
1428           /* GET request was terminated, so disconnect session */
1429           http_client_plugin_session_disconnect (plugin, s);
1430         }
1431       }
1432       else
1433         GNUNET_break (0); /* Must not happen */
1434
1435       GNUNET_STATISTICS_set (plugin->env->stats,
1436                              HTTP_STAT_STR_CONNECTIONS,
1437                              plugin->cur_requests,
1438                              GNUNET_NO);
1439     }
1440   }
1441   while (mret == CURLM_CALL_MULTI_PERFORM);
1442   client_schedule (plugin, GNUNET_NO);
1443 }
1444
1445
1446 #ifdef TCP_STEALTH
1447 /**
1448  * Open TCP socket with TCP STEALTH enabled.
1449  *
1450  * @param clientp our `struct GNUNET_ATS_Session *`
1451  * @param purpose why does curl want to open a socket
1452  * @param address what kind of socket does curl want to have opened?
1453  * @return opened socket
1454  */
1455 static curl_socket_t
1456 open_tcp_stealth_socket_cb (void *clientp,
1457                             curlsocktype purpose,
1458                             struct curl_sockaddr *address)
1459 {
1460   struct GNUNET_ATS_Session *s = clientp;
1461   int ret;
1462
1463   switch (purpose)
1464   {
1465   case CURLSOCKTYPE_IPCXN:
1466     ret = socket (address->family,
1467                   address->socktype,
1468                   address->protocol);
1469     if (-1 == ret)
1470       return CURL_SOCKET_BAD;
1471     if ( ( (SOCK_STREAM != address->socktype) ||
1472            ( (0 != address->protocol) &&
1473              (IPPROTO_TCP != address->protocol))) )
1474       return (curl_socket_t) ret;
1475     if ( (0 != setsockopt (ret,
1476                            IPPROTO_TCP,
1477                            TCP_STEALTH,
1478                            &s->address->peer,
1479                            sizeof (struct GNUNET_PeerIdentity))) )
1480     {
1481       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1482                   _("TCP_STEALTH not supported on this platform.\n"));
1483       (void) close (ret);
1484       return CURL_SOCKET_BAD;
1485     }
1486     return (curl_socket_t) ret;
1487   case CURLSOCKTYPE_ACCEPT:
1488     GNUNET_break (0);
1489     return CURL_SOCKET_BAD;
1490     break;
1491   case CURLSOCKTYPE_LAST:
1492     GNUNET_break (0);
1493     return CURL_SOCKET_BAD;
1494   default:
1495     GNUNET_break (0);
1496     return CURL_SOCKET_BAD;
1497   }
1498 }
1499 #endif
1500
1501
1502 /**
1503  * Connect GET request for a session
1504  *
1505  * @param s the session to connect
1506  * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
1507  */
1508 static int
1509 client_connect_get (struct GNUNET_ATS_Session *s)
1510 {
1511   CURLMcode mret;
1512   struct HttpAddress *ha;
1513   uint32_t options;
1514
1515   ha = (struct HttpAddress *) s->address->address;
1516   options = ntohl (ha->options);
1517   /* create get request */
1518   s->get.easyhandle = curl_easy_init ();
1519   s->get.s = s;
1520   if (0 != (options & HTTP_OPTIONS_TCP_STEALTH))
1521   {
1522 #ifdef TCP_STEALTH
1523     curl_easy_setopt (s->get.easyhandle,
1524                       CURLOPT_OPENSOCKETFUNCTION,
1525                       &open_tcp_stealth_socket_cb);
1526     curl_easy_setopt (s->get.easyhandle,
1527                       CURLOPT_OPENSOCKETDATA,
1528                       s);
1529 #else
1530     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1531                 "Cannot connect, TCP STEALTH needed and not supported by kernel.\n");
1532     curl_easy_cleanup (s->get.easyhandle);
1533     s->get.easyhandle = NULL;
1534     s->get.s = NULL;
1535     return GNUNET_SYSERR;
1536 #endif
1537   }
1538
1539 #if VERBOSE_CURL
1540   curl_easy_setopt (s->get.easyhandle,
1541                     CURLOPT_VERBOSE,
1542                     1L);
1543   curl_easy_setopt (s->get.easyhandle,
1544                     CURLOPT_DEBUGFUNCTION,
1545                     &client_log);
1546   curl_easy_setopt (s->get.easyhandle,
1547                     CURLOPT_DEBUGDATA,
1548                     &s->get);
1549 #endif
1550 #if BUILD_HTTPS
1551   curl_easy_setopt (s->get.easyhandle, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
1552   {
1553     if (HTTP_OPTIONS_VERIFY_CERTIFICATE ==
1554         (options & HTTP_OPTIONS_VERIFY_CERTIFICATE))
1555     {
1556       curl_easy_setopt (s->get.easyhandle,
1557                         CURLOPT_SSL_VERIFYPEER, 1L);
1558       curl_easy_setopt (s->get.easyhandle,
1559                         CURLOPT_SSL_VERIFYHOST,
1560                         2L);
1561     }
1562     else
1563     {
1564       curl_easy_setopt (s->get.easyhandle,
1565                         CURLOPT_SSL_VERIFYPEER,
1566                         0L);
1567       curl_easy_setopt (s->get.easyhandle,
1568                         CURLOPT_SSL_VERIFYHOST,
1569                         0L);
1570     }
1571   }
1572   curl_easy_setopt (s->get.easyhandle,
1573                     CURLOPT_PROTOCOLS,
1574                     CURLPROTO_HTTPS);
1575   curl_easy_setopt (s->get.easyhandle,
1576                     CURLOPT_REDIR_PROTOCOLS,
1577                     CURLPROTO_HTTPS);
1578 #else
1579   curl_easy_setopt (s->get.easyhandle,
1580                     CURLOPT_PROTOCOLS,
1581                     CURLPROTO_HTTP);
1582   curl_easy_setopt (s->get.easyhandle,
1583                     CURLOPT_REDIR_PROTOCOLS,
1584                     CURLPROTO_HTTP);
1585 #endif
1586
1587   if (NULL != s->plugin->proxy_hostname)
1588   {
1589     curl_easy_setopt (s->get.easyhandle,
1590                       CURLOPT_PROXY,
1591                       s->plugin->proxy_hostname);
1592     curl_easy_setopt (s->get.easyhandle,
1593                       CURLOPT_PROXYTYPE,
1594                       s->plugin->proxytype);
1595     if (NULL != s->plugin->proxy_username)
1596       curl_easy_setopt (s->get.easyhandle,
1597                         CURLOPT_PROXYUSERNAME,
1598                         s->plugin->proxy_username);
1599     if (NULL != s->plugin->proxy_password)
1600       curl_easy_setopt (s->get.easyhandle,
1601                         CURLOPT_PROXYPASSWORD,
1602                         s->plugin->proxy_password);
1603     if (GNUNET_YES == s->plugin->proxy_use_httpproxytunnel)
1604       curl_easy_setopt (s->get.easyhandle,
1605                         CURLOPT_HTTPPROXYTUNNEL,
1606                         s->plugin->proxy_use_httpproxytunnel);
1607   }
1608
1609   if (GNUNET_YES == s->plugin->emulate_xhr)
1610   {
1611     char *url;
1612
1613     GNUNET_asprintf (&url,
1614                      "%s,1",
1615                      s->url);
1616     curl_easy_setopt (s->get.easyhandle,
1617                       CURLOPT_URL,
1618                       url);
1619     GNUNET_free(url);
1620   }
1621   else
1622   {
1623     curl_easy_setopt (s->get.easyhandle,
1624                       CURLOPT_URL,
1625                       s->url);
1626   }
1627   curl_easy_setopt (s->get.easyhandle,
1628                     CURLOPT_READFUNCTION,
1629                     &client_send_cb);
1630   curl_easy_setopt (s->get.easyhandle,
1631                     CURLOPT_READDATA,
1632                     s);
1633   curl_easy_setopt (s->get.easyhandle,
1634                     CURLOPT_WRITEFUNCTION,
1635                     &client_receive);
1636   curl_easy_setopt (s->get.easyhandle,
1637                     CURLOPT_WRITEDATA,
1638                     s);
1639   /* No timeout by default, timeout done with session timeout */
1640   curl_easy_setopt (s->get.easyhandle,
1641                     CURLOPT_TIMEOUT,
1642                     0L);
1643   curl_easy_setopt (s->get.easyhandle,
1644                     CURLOPT_PRIVATE, s);
1645   curl_easy_setopt (s->get.easyhandle,
1646                     CURLOPT_CONNECTTIMEOUT_MS,
1647                     (long) (HTTP_CLIENT_NOT_VALIDATED_TIMEOUT.rel_value_us / 1000LL));
1648   curl_easy_setopt (s->get.easyhandle, CURLOPT_BUFFERSIZE,
1649                     2 * GNUNET_SERVER_MAX_MESSAGE_SIZE);
1650 #if CURL_TCP_NODELAY
1651   curl_easy_setopt (ps->recv_endpoint,
1652                     CURLOPT_TCP_NODELAY,
1653                     1L);
1654 #endif
1655   curl_easy_setopt (s->get.easyhandle,
1656                     CURLOPT_FOLLOWLOCATION,
1657                     0L);
1658
1659   mret = curl_multi_add_handle (s->plugin->curl_multi_handle,
1660                                 s->get.easyhandle);
1661   if (CURLM_OK != mret)
1662   {
1663     LOG (GNUNET_ERROR_TYPE_ERROR,
1664          "Session %p : Failed to add GET handle to multihandle: `%s'\n",
1665          s,
1666          curl_multi_strerror (mret));
1667     curl_easy_cleanup (s->get.easyhandle);
1668     s->get.easyhandle = NULL;
1669     s->get.s = NULL;
1670     GNUNET_break (0);
1671     return GNUNET_SYSERR;
1672   }
1673   s->plugin->cur_requests++;
1674   LOG (GNUNET_ERROR_TYPE_INFO,
1675        "GET request `%s' established, number of requests increased to %u\n",
1676        s->url,
1677        s->plugin->cur_requests);
1678   return GNUNET_OK;
1679 }
1680
1681
1682 /**
1683  * Connect a HTTP put request
1684  *
1685  * @param s the session to connect
1686  * @return #GNUNET_SYSERR for hard failure, #GNUNET_OK for ok
1687  */
1688 static int
1689 client_connect_put (struct GNUNET_ATS_Session *s)
1690 {
1691   CURLMcode mret;
1692   struct HttpAddress *ha;
1693   uint32_t options;
1694
1695   ha = (struct HttpAddress *) s->address->address;
1696   options = ntohl (ha->options);
1697   /* create put request */
1698   LOG (GNUNET_ERROR_TYPE_DEBUG,
1699        "Session %p: Init PUT handle\n",
1700        s);
1701   s->put.easyhandle = curl_easy_init ();
1702   s->put.s = s;
1703 #if VERBOSE_CURL
1704   curl_easy_setopt (s->put.easyhandle,
1705                     CURLOPT_VERBOSE,
1706                     1L);
1707   curl_easy_setopt (s->put.easyhandle,
1708                     CURLOPT_DEBUGFUNCTION,
1709                     &client_log);
1710   curl_easy_setopt (s->put.easyhandle,
1711                     CURLOPT_DEBUGDATA,
1712                     &s->put);
1713 #endif
1714   if (0 != (options & HTTP_OPTIONS_TCP_STEALTH))
1715   {
1716 #ifdef TCP_STEALTH
1717     curl_easy_setopt (s->put.easyhandle,
1718                       CURLOPT_OPENSOCKETFUNCTION,
1719                       &open_tcp_stealth_socket_cb);
1720     curl_easy_setopt (s->put.easyhandle,
1721                       CURLOPT_OPENSOCKETDATA,
1722                       s);
1723 #else
1724     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1725                 "Cannot connect, TCP STEALTH needed and not supported by kernel.\n");
1726     curl_easy_cleanup (s->put.easyhandle);
1727     s->put.easyhandle = NULL;
1728     s->put.s = NULL;
1729     s->put.state = H_DISCONNECTED;
1730     return GNUNET_SYSERR;
1731 #endif
1732   }
1733 #if BUILD_HTTPS
1734   curl_easy_setopt (s->put.easyhandle,
1735                     CURLOPT_SSLVERSION,
1736                     CURL_SSLVERSION_TLSv1);
1737   {
1738     struct HttpAddress *ha;
1739     ha = (struct HttpAddress *) s->address->address;
1740
1741     if (HTTP_OPTIONS_VERIFY_CERTIFICATE ==
1742         (ntohl (ha->options) & HTTP_OPTIONS_VERIFY_CERTIFICATE))
1743     {
1744       curl_easy_setopt (s->put.easyhandle,
1745                         CURLOPT_SSL_VERIFYPEER,
1746                         1L);
1747       curl_easy_setopt (s->put.easyhandle,
1748                         CURLOPT_SSL_VERIFYHOST,
1749                         2L);
1750     }
1751     else
1752     {
1753       curl_easy_setopt (s->put.easyhandle,
1754                         CURLOPT_SSL_VERIFYPEER,
1755                         0L);
1756       curl_easy_setopt (s->put.easyhandle,
1757                         CURLOPT_SSL_VERIFYHOST,
1758                         0L);
1759     }
1760   }
1761   curl_easy_setopt (s->put.easyhandle,
1762                     CURLOPT_PROTOCOLS,
1763                     CURLPROTO_HTTPS);
1764   curl_easy_setopt (s->put.easyhandle,
1765                     CURLOPT_REDIR_PROTOCOLS,
1766                     CURLPROTO_HTTPS);
1767 #else
1768   curl_easy_setopt (s->put.easyhandle,
1769                     CURLOPT_PROTOCOLS,
1770                     CURLPROTO_HTTP);
1771   curl_easy_setopt (s->put.easyhandle,
1772                     CURLOPT_REDIR_PROTOCOLS,
1773                     CURLPROTO_HTTP);
1774 #endif
1775   if (NULL != s->plugin->proxy_hostname)
1776   {
1777     curl_easy_setopt (s->put.easyhandle,
1778                       CURLOPT_PROXY,
1779                       s->plugin->proxy_hostname);
1780     curl_easy_setopt (s->put.easyhandle,
1781                       CURLOPT_PROXYTYPE,
1782                       s->plugin->proxytype);
1783     if (NULL != s->plugin->proxy_username)
1784       curl_easy_setopt (s->put.easyhandle,
1785                         CURLOPT_PROXYUSERNAME,
1786                         s->plugin->proxy_username);
1787     if (NULL != s->plugin->proxy_password)
1788       curl_easy_setopt (s->put.easyhandle,
1789                         CURLOPT_PROXYPASSWORD,
1790                         s->plugin->proxy_password);
1791     if (GNUNET_YES == s->plugin->proxy_use_httpproxytunnel)
1792       curl_easy_setopt (s->put.easyhandle,
1793                         CURLOPT_HTTPPROXYTUNNEL,
1794                         s->plugin->proxy_use_httpproxytunnel);
1795   }
1796
1797   curl_easy_setopt (s->put.easyhandle,
1798                     CURLOPT_URL,
1799                     s->url);
1800   curl_easy_setopt (s->put.easyhandle,
1801                     CURLOPT_UPLOAD,
1802                     1L);
1803   curl_easy_setopt (s->put.easyhandle,
1804                     CURLOPT_READFUNCTION,
1805                     &client_send_cb);
1806   curl_easy_setopt (s->put.easyhandle,
1807                     CURLOPT_READDATA,
1808                     s);
1809   curl_easy_setopt (s->put.easyhandle,
1810                     CURLOPT_WRITEFUNCTION,
1811                     &client_receive_put);
1812   curl_easy_setopt (s->put.easyhandle,
1813                     CURLOPT_WRITEDATA,
1814                     s);
1815   /* No timeout by default, timeout done with session timeout */
1816   curl_easy_setopt (s->put.easyhandle,
1817                     CURLOPT_TIMEOUT,
1818                     0L);
1819   curl_easy_setopt (s->put.easyhandle,
1820                     CURLOPT_PRIVATE,
1821                     s);
1822   curl_easy_setopt (s->put.easyhandle,
1823                     CURLOPT_CONNECTTIMEOUT_MS,
1824                     (long) (HTTP_CLIENT_NOT_VALIDATED_TIMEOUT.rel_value_us / 1000LL));
1825   curl_easy_setopt (s->put.easyhandle, CURLOPT_BUFFERSIZE,
1826                     2 * GNUNET_SERVER_MAX_MESSAGE_SIZE);
1827 #if CURL_TCP_NODELAY
1828   curl_easy_setopt (s->put.easyhandle, CURLOPT_TCP_NODELAY, 1);
1829 #endif
1830   mret = curl_multi_add_handle (s->plugin->curl_multi_handle,
1831                                 s->put.easyhandle);
1832   if (CURLM_OK != mret)
1833   {
1834     LOG (GNUNET_ERROR_TYPE_ERROR,
1835          "Session %p : Failed to add PUT handle to multihandle: `%s'\n",
1836          s, curl_multi_strerror (mret));
1837     curl_easy_cleanup (s->put.easyhandle);
1838     s->put.easyhandle = NULL;
1839     s->put.s = NULL;
1840     s->put.state = H_DISCONNECTED;
1841     return GNUNET_SYSERR;
1842   }
1843   s->put.state = H_CONNECTED;
1844   s->plugin->cur_requests++;
1845
1846   LOG  (GNUNET_ERROR_TYPE_INFO,
1847       "PUT request `%s' established, number of requests increased to %u\n",
1848       s->url, s->plugin->cur_requests);
1849
1850   return GNUNET_OK;
1851 }
1852
1853
1854 /**
1855  * Connect both PUT and GET request for a session
1856  *
1857  * @param s the session to connect
1858  * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
1859  */
1860 static int
1861 client_connect (struct GNUNET_ATS_Session *s)
1862 {
1863   struct HTTP_Client_Plugin *plugin = s->plugin;
1864   int res = GNUNET_OK;
1865
1866   /* create url */
1867   if (NULL ==
1868       http_common_plugin_address_to_string(plugin->protocol,
1869                                            s->address->address,
1870                                            s->address->address_length))
1871   {
1872     LOG (GNUNET_ERROR_TYPE_DEBUG,
1873          "Invalid address peer `%s'\n",
1874          GNUNET_i2s(&s->address->peer));
1875     return GNUNET_SYSERR;
1876   }
1877
1878   GNUNET_asprintf (&s->url,
1879                    "%s/%s;%u",
1880                    http_common_plugin_address_to_url (NULL,
1881                                                       s->address->address,
1882                                                       s->address->address_length),
1883                    GNUNET_i2s_full (plugin->env->my_identity),
1884                    plugin->last_tag);
1885
1886   plugin->last_tag++;
1887   LOG (GNUNET_ERROR_TYPE_DEBUG,
1888        "Initiating outbound session peer `%s' using address `%s'\n",
1889        GNUNET_i2s (&s->address->peer), s->url);
1890
1891   if (GNUNET_SYSERR == client_connect_get (s))
1892     return GNUNET_SYSERR;
1893   /* If we are emulating an XHR client then delay sending a PUT request until
1894    * there is something to send.
1895    */
1896   if (GNUNET_YES == plugin->emulate_xhr)
1897   {
1898     s->put.state = H_TMP_DISCONNECTED;
1899   }
1900   else if (GNUNET_SYSERR == client_connect_put (s))
1901     return GNUNET_SYSERR;
1902
1903   LOG (GNUNET_ERROR_TYPE_DEBUG,
1904        "Session %p: connected with GET %p and PUT %p\n",
1905        s, s->get.easyhandle,
1906        s->put.easyhandle);
1907   /* Perform connect */
1908   GNUNET_STATISTICS_set (plugin->env->stats,
1909                          HTTP_STAT_STR_CONNECTIONS,
1910                          plugin->cur_requests,
1911                          GNUNET_NO);
1912   /* Re-schedule since handles have changed */
1913   if (NULL != plugin->client_perform_task)
1914   {
1915     GNUNET_SCHEDULER_cancel (plugin->client_perform_task);
1916     plugin->client_perform_task = NULL;
1917   }
1918
1919   /* Schedule task to run immediately */
1920   plugin->client_perform_task = GNUNET_SCHEDULER_add_now (client_run,
1921                                                           plugin);
1922   return res;
1923 }
1924
1925
1926 /**
1927  * Function obtain the network type for a session
1928  *
1929  * @param cls closure (`struct Plugin*`)
1930  * @param session the session
1931  * @return the network type
1932  */
1933 static enum GNUNET_ATS_Network_Type
1934 http_client_plugin_get_network (void *cls,
1935                                 struct GNUNET_ATS_Session *session)
1936 {
1937   return session->scope;
1938 }
1939
1940
1941 /**
1942  * Function obtain the network type for an address.
1943  *
1944  * @param cls closure (`struct Plugin *`)
1945  * @param address the address
1946  * @return the network type
1947  */
1948 static enum GNUNET_ATS_Network_Type
1949 http_client_plugin_get_network_for_address (void *cls,
1950                                             const struct GNUNET_HELLO_Address *address)
1951 {
1952   struct HTTP_Client_Plugin *plugin = cls;
1953
1954   return http_common_get_network_for_address (plugin->env,
1955                                               address);
1956 }
1957
1958
1959 /**
1960  * Session was idle, so disconnect it
1961  *
1962  * @param cls the `struct GNUNET_ATS_Session` of the idle session
1963  */
1964 static void
1965 client_session_timeout (void *cls)
1966 {
1967   struct GNUNET_ATS_Session *s = cls;
1968   struct GNUNET_TIME_Relative left;
1969
1970   s->timeout_task = NULL;
1971   left = GNUNET_TIME_absolute_get_remaining (s->timeout);
1972   if (0 != left.rel_value_us)
1973   {
1974     /* not actually our turn yet, but let's at least update
1975        the monitor, it may think we're about to die ... */
1976     notify_session_monitor (s->plugin,
1977                             s,
1978                             GNUNET_TRANSPORT_SS_UPDATE);
1979     s->timeout_task = GNUNET_SCHEDULER_add_delayed (left,
1980                                                     &client_session_timeout,
1981                                                     s);
1982     return;
1983   }
1984   LOG (TIMEOUT_LOG,
1985        "Session %p was idle for %s, disconnecting\n",
1986        s,
1987        GNUNET_STRINGS_relative_time_to_string (HTTP_CLIENT_SESSION_TIMEOUT,
1988                                                GNUNET_YES));
1989   GNUNET_assert (GNUNET_OK ==
1990                  http_client_plugin_session_disconnect (s->plugin,
1991                                                  s));
1992 }
1993
1994
1995 /**
1996  * Creates a new outbound session the transport service will use to
1997  * send data to the peer
1998  *
1999  * @param cls the plugin
2000  * @param address the address
2001  * @return the session or NULL of max connections exceeded
2002  */
2003 static struct GNUNET_ATS_Session *
2004 http_client_plugin_get_session (void *cls,
2005                                 const struct GNUNET_HELLO_Address *address)
2006 {
2007   struct HTTP_Client_Plugin *plugin = cls;
2008   struct GNUNET_ATS_Session *s;
2009   struct sockaddr *sa;
2010   enum GNUNET_ATS_Network_Type net_type;
2011   size_t salen = 0;
2012   int res;
2013
2014   GNUNET_assert (NULL != address->address);
2015
2016   /* find existing session */
2017   s = client_lookup_session (plugin, address);
2018   if (NULL != s)
2019     return s;
2020
2021   /* create a new session */
2022   if (plugin->max_requests <= plugin->cur_requests)
2023   {
2024     LOG (GNUNET_ERROR_TYPE_WARNING,
2025          "Maximum number of requests (%u) reached: "
2026          "cannot connect to peer `%s'\n",
2027          plugin->max_requests,
2028          GNUNET_i2s (&address->peer));
2029     return NULL;
2030   }
2031
2032   /* Determine network location */
2033   net_type = GNUNET_ATS_NET_UNSPECIFIED;
2034   sa = http_common_socket_from_address (address->address,
2035                                         address->address_length,
2036                                         &res);
2037   if (GNUNET_SYSERR == res)
2038     return NULL;
2039   if (GNUNET_YES == res)
2040   {
2041     GNUNET_assert (NULL != sa);
2042     if (AF_INET == sa->sa_family)
2043     {
2044       salen = sizeof (struct sockaddr_in);
2045     }
2046     else if (AF_INET6 == sa->sa_family)
2047     {
2048       salen = sizeof (struct sockaddr_in6);
2049     }
2050     net_type = plugin->env->get_address_type (plugin->env->cls, sa, salen);
2051     GNUNET_free (sa);
2052   }
2053   else if (GNUNET_NO == res)
2054   {
2055     /* Cannot convert to sockaddr -> is external hostname */
2056     net_type = GNUNET_ATS_NET_WAN;
2057   }
2058   if (GNUNET_ATS_NET_UNSPECIFIED == net_type)
2059   {
2060     GNUNET_break (0);
2061     return NULL;
2062   }
2063
2064   s = GNUNET_new (struct GNUNET_ATS_Session);
2065   s->plugin = plugin;
2066   s->address = GNUNET_HELLO_address_copy (address);
2067   s->scope = net_type;
2068
2069   s->put.state = H_NOT_CONNECTED;
2070   s->timeout = GNUNET_TIME_relative_to_absolute (HTTP_CLIENT_SESSION_TIMEOUT);
2071   s->timeout_task =  GNUNET_SCHEDULER_add_delayed (HTTP_CLIENT_SESSION_TIMEOUT,
2072                                                    &client_session_timeout,
2073                                                    s);
2074   LOG (GNUNET_ERROR_TYPE_DEBUG,
2075        "Created new session %p for `%s' address `%s''\n",
2076        s,
2077        http_common_plugin_address_to_string (plugin->protocol,
2078                                              s->address->address,
2079                                              s->address->address_length),
2080        GNUNET_i2s (&s->address->peer));
2081
2082   /* add new session */
2083   (void) GNUNET_CONTAINER_multipeermap_put (plugin->sessions,
2084                                             &s->address->peer,
2085                                             s,
2086                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2087   /* initiate new connection */
2088   if (GNUNET_SYSERR == client_connect (s))
2089   {
2090     LOG (GNUNET_ERROR_TYPE_ERROR,
2091          "Cannot connect to peer `%s' address `%s''\n",
2092          http_common_plugin_address_to_string (plugin->protocol,
2093              s->address->address, s->address->address_length),
2094              GNUNET_i2s (&s->address->peer));
2095     client_delete_session (s);
2096     return NULL;
2097   }
2098   notify_session_monitor (plugin,
2099                           s,
2100                           GNUNET_TRANSPORT_SS_INIT);
2101   notify_session_monitor (plugin,
2102                           s,
2103                           GNUNET_TRANSPORT_SS_UP); /* or handshake? */
2104   return s;
2105 }
2106
2107
2108 /**
2109  * Setup http_client plugin
2110  *
2111  * @param plugin the plugin handle
2112  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
2113  */
2114 static int
2115 client_start (struct HTTP_Client_Plugin *plugin)
2116 {
2117   curl_global_init (CURL_GLOBAL_ALL);
2118   plugin->curl_multi_handle = curl_multi_init ();
2119
2120   if (NULL == plugin->curl_multi_handle)
2121   {
2122     LOG (GNUNET_ERROR_TYPE_ERROR,
2123          _("Could not initialize curl multi handle, failed to start %s plugin!\n"),
2124          plugin->name);
2125     return GNUNET_SYSERR;
2126   }
2127   return GNUNET_OK;
2128 }
2129
2130
2131 /**
2132  * Another peer has suggested an address for this
2133  * peer and transport plugin.  Check that this could be a valid
2134  * address.  If so, consider adding it to the list
2135  * of addresses.
2136  *
2137  * @param cls closure with the `struct Plugin`
2138  * @param addr pointer to the address
2139  * @param addrlen length of @a addr
2140  * @return #GNUNET_OK if this is a plausible address for this peer
2141  *         and transport; always returns #GNUNET_NO (this is the client!)
2142  */
2143 static int
2144 http_client_plugin_address_suggested (void *cls,
2145                                       const void *addr,
2146                                       size_t addrlen)
2147 {
2148   /* A HTTP/S client does not have any valid address so:*/
2149   return GNUNET_NO;
2150 }
2151
2152
2153 /**
2154  * Exit point from the plugin.
2155  *
2156  * @param cls api as closure
2157  * @return NULL
2158  */
2159 void *
2160 LIBGNUNET_PLUGIN_TRANSPORT_DONE (void *cls)
2161 {
2162   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2163   struct HTTP_Client_Plugin *plugin = api->cls;
2164
2165   if (NULL == api->cls)
2166   {
2167     /* Stub shutdown */
2168     GNUNET_free (api);
2169     return NULL;
2170   }
2171   LOG (GNUNET_ERROR_TYPE_DEBUG,
2172        _("Shutting down plugin `%s'\n"),
2173        plugin->name);
2174   GNUNET_CONTAINER_multipeermap_iterate (plugin->sessions,
2175                                          &destroy_session_cb,
2176                                          plugin);
2177   if (NULL != plugin->client_perform_task)
2178   {
2179     GNUNET_SCHEDULER_cancel (plugin->client_perform_task);
2180     plugin->client_perform_task = NULL;
2181   }
2182   if (NULL != plugin->curl_multi_handle)
2183   {
2184     curl_multi_cleanup (plugin->curl_multi_handle);
2185     plugin->curl_multi_handle = NULL;
2186   }
2187   curl_global_cleanup ();
2188   LOG (GNUNET_ERROR_TYPE_DEBUG,
2189        _("Shutdown for plugin `%s' complete\n"),
2190        plugin->name);
2191   GNUNET_CONTAINER_multipeermap_destroy (plugin->sessions);
2192   GNUNET_free_non_null (plugin->proxy_hostname);
2193   GNUNET_free_non_null (plugin->proxy_username);
2194   GNUNET_free_non_null (plugin->proxy_password);
2195   GNUNET_free (plugin);
2196   GNUNET_free (api);
2197   return NULL;
2198 }
2199
2200
2201 /**
2202  * Configure plugin
2203  *
2204  * @param plugin the plugin handle
2205  * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
2206  */
2207 static int
2208 client_configure_plugin (struct HTTP_Client_Plugin *plugin)
2209 {
2210   unsigned long long max_requests;
2211   char *proxy_type;
2212
2213   /* Optional parameters */
2214   if (GNUNET_OK !=
2215       GNUNET_CONFIGURATION_get_value_number (plugin->env->cfg,
2216                                              plugin->name,
2217                                              "MAX_CONNECTIONS",
2218                                              &max_requests))
2219     max_requests = 128;
2220   plugin->max_requests = max_requests;
2221
2222   LOG (GNUNET_ERROR_TYPE_DEBUG,
2223        _("Maximum number of requests is %u\n"),
2224        plugin->max_requests);
2225
2226   /* Read proxy configuration */
2227   if (GNUNET_OK ==
2228       GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
2229                                              plugin->name,
2230                                              "PROXY",
2231                                              &plugin->proxy_hostname))
2232   {
2233     LOG (GNUNET_ERROR_TYPE_DEBUG,
2234          "Found proxy host: `%s'\n",
2235          plugin->proxy_hostname);
2236     /* proxy username */
2237     if (GNUNET_OK ==
2238         GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
2239                                                plugin->name,
2240                                                "PROXY_USERNAME",
2241                                                &plugin->proxy_username))
2242     {
2243       LOG (GNUNET_ERROR_TYPE_DEBUG,
2244            "Found proxy username name: `%s'\n",
2245            plugin->proxy_username);
2246     }
2247
2248     /* proxy password */
2249     if (GNUNET_OK ==
2250         GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
2251                                                plugin->name,
2252                                                "PROXY_PASSWORD",
2253                                                &plugin->proxy_password))
2254     {
2255       LOG (GNUNET_ERROR_TYPE_DEBUG,
2256            "Found proxy password name: `%s'\n",
2257            plugin->proxy_password);
2258     }
2259
2260     /* proxy type */
2261     if (GNUNET_OK ==
2262         GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
2263                                                plugin->name,
2264                                                "PROXY_TYPE",
2265                                                &proxy_type))
2266     {
2267       GNUNET_STRINGS_utf8_toupper (proxy_type, proxy_type);
2268
2269       if (0 == strcmp(proxy_type, "HTTP"))
2270         plugin->proxytype = CURLPROXY_HTTP;
2271       else if (0 == strcmp(proxy_type, "SOCKS4"))
2272         plugin->proxytype = CURLPROXY_SOCKS4;
2273       else if (0 == strcmp(proxy_type, "SOCKS5"))
2274         plugin->proxytype = CURLPROXY_SOCKS5;
2275       else if (0 == strcmp(proxy_type, "SOCKS4A"))
2276         plugin->proxytype = CURLPROXY_SOCKS4A;
2277       else if (0 == strcmp(proxy_type, "SOCKS5_HOSTNAME "))
2278         plugin->proxytype = CURLPROXY_SOCKS5_HOSTNAME ;
2279       else
2280       {
2281         LOG (GNUNET_ERROR_TYPE_ERROR,
2282              _("Invalid proxy type: `%s', disabling proxy! Check configuration!\n"),
2283              proxy_type);
2284
2285         GNUNET_free (proxy_type);
2286         GNUNET_free (plugin->proxy_hostname);
2287         plugin->proxy_hostname = NULL;
2288         GNUNET_free_non_null (plugin->proxy_username);
2289         plugin->proxy_username = NULL;
2290         GNUNET_free_non_null (plugin->proxy_password);
2291         plugin->proxy_password = NULL;
2292
2293         return GNUNET_SYSERR;
2294       }
2295
2296       LOG (GNUNET_ERROR_TYPE_DEBUG,
2297            "Found proxy type: `%s'\n",
2298            proxy_type);
2299     }
2300
2301     /* proxy http tunneling */
2302     plugin->proxy_use_httpproxytunnel
2303       = GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg,
2304                                               plugin->name,
2305                                               "PROXY_HTTP_TUNNELING");
2306     if (GNUNET_SYSERR == plugin->proxy_use_httpproxytunnel)
2307       plugin->proxy_use_httpproxytunnel = GNUNET_NO;
2308
2309     GNUNET_free_non_null (proxy_type);
2310   }
2311
2312   /* Should we emulate an XHR client for testing? */
2313   plugin->emulate_xhr
2314     = GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg,
2315                                             plugin->name,
2316                                             "EMULATE_XHR");
2317   return GNUNET_OK;
2318 }
2319
2320
2321 /**
2322  * Function to convert an address to a human-readable string.
2323  *
2324  * @param cls closure
2325  * @param addr address to convert
2326  * @param addrlen address length
2327  * @return res string if conversion was successful, NULL otherwise
2328  */
2329 static const char *
2330 http_client_plugin_address_to_string (void *cls,
2331                                       const void *addr,
2332                                       size_t addrlen)
2333 {
2334   return http_common_plugin_address_to_string (PLUGIN_NAME,
2335                                                addr,
2336                                                addrlen);
2337 }
2338
2339
2340 /**
2341  * Function that will be called whenever the transport service wants to
2342  * notify the plugin that a session is still active and in use and
2343  * therefore the session timeout for this session has to be updated
2344  *
2345  * @param cls closure
2346  * @param peer which peer was the session for
2347  * @param session which session is being updated
2348  */
2349 static void
2350 http_client_plugin_update_session_timeout (void *cls,
2351                                            const struct GNUNET_PeerIdentity *peer,
2352                                            struct GNUNET_ATS_Session *session)
2353 {
2354   client_reschedule_session_timeout (session);
2355 }
2356
2357
2358 /**
2359  * Function that will be called whenever the transport service wants to
2360  * notify the plugin that the inbound quota changed and that the plugin
2361  * should update it's delay for the next receive value
2362  *
2363  * @param cls closure
2364  * @param peer which peer was the session for
2365  * @param s which session is being updated
2366  * @param delay new delay to use for receiving
2367  */
2368 static void
2369 http_client_plugin_update_inbound_delay (void *cls,
2370                                          const struct GNUNET_PeerIdentity *peer,
2371                                          struct GNUNET_ATS_Session *s,
2372                                          struct GNUNET_TIME_Relative delay)
2373 {
2374   s->next_receive = GNUNET_TIME_relative_to_absolute (delay);
2375   LOG (GNUNET_ERROR_TYPE_DEBUG,
2376        "New inbound delay %s\n",
2377        GNUNET_STRINGS_relative_time_to_string (delay,
2378                                                GNUNET_NO));
2379   if (s->recv_wakeup_task != NULL)
2380   {
2381     GNUNET_SCHEDULER_cancel (s->recv_wakeup_task);
2382     s->recv_wakeup_task = GNUNET_SCHEDULER_add_delayed (delay,
2383         &client_wake_up, s);
2384   }
2385 }
2386
2387
2388 /**
2389  * Return information about the given session to the
2390  * monitor callback.
2391  *
2392  * @param cls the `struct Plugin` with the monitor callback (`sic`)
2393  * @param peer peer we send information about
2394  * @param value our `struct GNUNET_ATS_Session` to send information about
2395  * @return #GNUNET_OK (continue to iterate)
2396  */
2397 static int
2398 send_session_info_iter (void *cls,
2399                         const struct GNUNET_PeerIdentity *peer,
2400                         void *value)
2401 {
2402   struct HTTP_Client_Plugin *plugin = cls;
2403   struct GNUNET_ATS_Session *session = value;
2404
2405   notify_session_monitor (plugin,
2406                           session,
2407                           GNUNET_TRANSPORT_SS_INIT);
2408   notify_session_monitor (plugin,
2409                           session,
2410                           GNUNET_TRANSPORT_SS_UP); /* FIXME: or handshake? */
2411   return GNUNET_OK;
2412 }
2413
2414
2415 /**
2416  * Begin monitoring sessions of a plugin.  There can only
2417  * be one active monitor per plugin (i.e. if there are
2418  * multiple monitors, the transport service needs to
2419  * multiplex the generated events over all of them).
2420  *
2421  * @param cls closure of the plugin
2422  * @param sic callback to invoke, NULL to disable monitor;
2423  *            plugin will being by iterating over all active
2424  *            sessions immediately and then enter monitor mode
2425  * @param sic_cls closure for @a sic
2426  */
2427 static void
2428 http_client_plugin_setup_monitor (void *cls,
2429                                   GNUNET_TRANSPORT_SessionInfoCallback sic,
2430                                   void *sic_cls)
2431 {
2432   struct HTTP_Client_Plugin *plugin = cls;
2433
2434   plugin->sic = sic;
2435   plugin->sic_cls = sic_cls;
2436   if (NULL != sic)
2437   {
2438     GNUNET_CONTAINER_multipeermap_iterate (plugin->sessions,
2439                                            &send_session_info_iter,
2440                                            plugin);
2441     /* signal end of first iteration */
2442     sic (sic_cls, NULL, NULL);
2443   }
2444 }
2445
2446
2447 /**
2448  * Entry point for the plugin.
2449  */
2450 void *
2451 LIBGNUNET_PLUGIN_TRANSPORT_INIT (void *cls)
2452 {
2453   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2454   struct GNUNET_TRANSPORT_PluginFunctions *api;
2455   struct HTTP_Client_Plugin *plugin;
2456
2457   if (NULL == env->receive)
2458   {
2459     /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
2460        initialze the plugin or the API */
2461     api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
2462     api->cls = NULL;
2463     api->address_to_string = &http_client_plugin_address_to_string;
2464     api->string_to_address = &http_common_plugin_string_to_address;
2465     api->address_pretty_printer = &http_common_plugin_address_pretty_printer;
2466     return api;
2467   }
2468
2469   plugin = GNUNET_new (struct HTTP_Client_Plugin);
2470   plugin->env = env;
2471   plugin->sessions = GNUNET_CONTAINER_multipeermap_create (128,
2472                                                            GNUNET_YES);
2473   api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
2474   api->cls = plugin;
2475   api->send = &http_client_plugin_send;
2476   api->disconnect_session = &http_client_plugin_session_disconnect;
2477   api->query_keepalive_factor = &http_client_query_keepalive_factor;
2478   api->disconnect_peer = &http_client_plugin_peer_disconnect;
2479   api->check_address = &http_client_plugin_address_suggested;
2480   api->get_session = &http_client_plugin_get_session;
2481   api->address_to_string = &http_client_plugin_address_to_string;
2482   api->string_to_address = &http_common_plugin_string_to_address;
2483   api->address_pretty_printer = &http_common_plugin_address_pretty_printer;
2484   api->get_network = &http_client_plugin_get_network;
2485   api->get_network_for_address = &http_client_plugin_get_network_for_address;
2486   api->update_session_timeout = &http_client_plugin_update_session_timeout;
2487   api->update_inbound_delay = &http_client_plugin_update_inbound_delay;
2488   api->setup_monitor = &http_client_plugin_setup_monitor;
2489 #if BUILD_HTTPS
2490   plugin->name = "transport-https_client";
2491   plugin->protocol = "https";
2492 #else
2493   plugin->name = "transport-http_client";
2494   plugin->protocol = "http";
2495 #endif
2496   plugin->last_tag = 1;
2497
2498   if (GNUNET_SYSERR == client_configure_plugin (plugin))
2499   {
2500     LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
2501     return NULL;
2502   }
2503
2504   /* Start client */
2505   if (GNUNET_SYSERR == client_start (plugin))
2506   {
2507     LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
2508     return NULL;
2509   }
2510   return api;
2511 }
2512
2513 /* end of plugin_transport_http_client.c */