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