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