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