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