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