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