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