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