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