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