fix peer ids
[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
916   if (GNUNET_YES != client_exist_session(p, s))
917   {
918     GNUNET_break (0);
919     return GNUNET_OK;
920   }
921   plugin = s->plugin;
922
923   atsi.type = htonl (GNUNET_ATS_NETWORK_TYPE);
924   atsi.value = s->ats_address_network_type;
925   GNUNET_break (s->ats_address_network_type != ntohl (GNUNET_ATS_NET_UNSPECIFIED));
926   delay = s->plugin->env->receive (plugin->env->cls, &s->target, message,
927                                    s, (const char *) s->addr, s->addrlen);
928
929   plugin->env->update_address_metrics (plugin->env->cls,
930                                        &s->target,
931                                        s->addr,
932                                        s->addrlen,
933                                        s,
934                                        &atsi, 1);
935
936   GNUNET_asprintf (&stat_txt, "# bytes received via %s_client", plugin->protocol);
937   GNUNET_STATISTICS_update (plugin->env->stats,
938                             stat_txt, ntohs(message->size), GNUNET_NO);
939   GNUNET_free (stat_txt);
940
941   s->next_receive =
942       GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (), delay);
943
944   if (GNUNET_TIME_absolute_get ().abs_value_us < s->next_receive.abs_value_us)
945   {
946     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
947                      "Client: peer `%s' address `%s' next read delayed for %s\n",
948                      GNUNET_i2s (&s->target),
949                      http_common_plugin_address_to_string (NULL,
950                                                            s->plugin->protocol, 
951                                                            s->addr, s->addrlen),
952                      GNUNET_STRINGS_relative_time_to_string (delay,
953                                                              GNUNET_YES));
954   }
955   client_reschedule_session_timeout (s);
956   return GNUNET_OK;
957 }
958
959
960 /**
961  * Callback method used with libcurl when data for a PUT connection are
962  * received. We do not expect data here, so we just dismiss it
963  *
964  * @param stream pointer where to write data
965  * @param size size of an individual element
966  * @param nmemb count of elements that can be written to the buffer
967  * @param cls destination pointer, passed to the libcurl handle
968  * @return bytes read from stream
969  */
970 static size_t
971 client_receive_put (void *stream, size_t size, size_t nmemb, void *cls)
972 {
973   return size * nmemb;
974 }
975
976
977 /**
978  * Callback method used with libcurl when data for a GET connection are
979  * received. Forward to MST
980  *
981  * @param stream pointer where to write data
982  * @param size size of an individual element
983  * @param nmemb count of elements that can be written to the buffer
984  * @param cls destination pointer, passed to the libcurl handle
985  * @return bytes read from stream
986  */
987 static size_t
988 client_receive (void *stream, size_t size, size_t nmemb, void *cls)
989 {
990   struct Session *s = cls;
991   struct GNUNET_TIME_Absolute now;
992   size_t len = size * nmemb;
993
994   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, s->plugin->name,
995                    "Session %p / connection %p: Received %u bytes from peer `%s'\n",
996                    s, s->client_get,
997                    len, GNUNET_i2s (&s->target));
998   now = GNUNET_TIME_absolute_get ();
999   if (now.abs_value_us < s->next_receive.abs_value_us)
1000   {
1001     struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
1002     struct GNUNET_TIME_Relative delta =
1003         GNUNET_TIME_absolute_get_difference (now, s->next_receive);
1004     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, s->plugin->name,
1005                      "Session %p / connection %p: No inbound bandwidth available! Next read was delayed for %s\n",
1006                      s, s->client_get, 
1007                      GNUNET_STRINGS_relative_time_to_string (delta,
1008                                                              GNUNET_YES));
1009     if (s->recv_wakeup_task != GNUNET_SCHEDULER_NO_TASK)
1010     {
1011       GNUNET_SCHEDULER_cancel (s->recv_wakeup_task);
1012       s->recv_wakeup_task = GNUNET_SCHEDULER_NO_TASK;
1013     }
1014     s->recv_wakeup_task =
1015         GNUNET_SCHEDULER_add_delayed (delta, &client_wake_up, s);
1016     return CURL_WRITEFUNC_PAUSE;
1017   }
1018   if (NULL == s->msg_tk)
1019     s->msg_tk = GNUNET_SERVER_mst_create (&client_receive_mst_cb, s);
1020   GNUNET_SERVER_mst_receive (s->msg_tk, s, stream, len, GNUNET_NO, GNUNET_NO);
1021   return len;
1022 }
1023
1024
1025 /**
1026  * Task performing curl operations
1027  *
1028  * @param cls plugin as closure
1029  * @param tc gnunet scheduler task context
1030  */
1031 static void
1032 client_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1033
1034
1035 /**
1036  * Function setting up file descriptors and scheduling task to run
1037  *
1038  * @param plugin the plugin as closure
1039  * @param now schedule task in 1ms, regardless of what curl may say
1040  * @return GNUNET_SYSERR for hard failure, GNUNET_OK for ok
1041  */
1042 static int
1043 client_schedule (struct HTTP_Client_Plugin *plugin, int now)
1044 {
1045   fd_set rs;
1046   fd_set ws;
1047   fd_set es;
1048   int max;
1049   struct GNUNET_NETWORK_FDSet *grs;
1050   struct GNUNET_NETWORK_FDSet *gws;
1051   long to;
1052   CURLMcode mret;
1053   struct GNUNET_TIME_Relative timeout;
1054
1055   /* Cancel previous scheduled task */
1056   if (plugin->client_perform_task != GNUNET_SCHEDULER_NO_TASK)
1057   {
1058     GNUNET_SCHEDULER_cancel (plugin->client_perform_task);
1059     plugin->client_perform_task = GNUNET_SCHEDULER_NO_TASK;
1060   }
1061   max = -1;
1062   FD_ZERO (&rs);
1063   FD_ZERO (&ws);
1064   FD_ZERO (&es);
1065   mret = curl_multi_fdset (plugin->curl_multi_handle, &rs, &ws, &es, &max);
1066   if (mret != CURLM_OK)
1067   {
1068     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("%s failed at %s:%d: `%s'\n"),
1069                 "curl_multi_fdset", __FILE__, __LINE__,
1070                 curl_multi_strerror (mret));
1071     return GNUNET_SYSERR;
1072   }
1073   mret = curl_multi_timeout (plugin->curl_multi_handle, &to);
1074   if (to == -1)
1075     timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1);
1076   else
1077     timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, to);
1078   if (now == GNUNET_YES)
1079     timeout = GNUNET_TIME_UNIT_MILLISECONDS;
1080
1081   if (mret != CURLM_OK)
1082   {
1083     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("%s failed at %s:%d: `%s'\n"),
1084                 "curl_multi_timeout", __FILE__, __LINE__,
1085                 curl_multi_strerror (mret));
1086     return GNUNET_SYSERR;
1087   }
1088
1089   grs = GNUNET_NETWORK_fdset_create ();
1090   gws = GNUNET_NETWORK_fdset_create ();
1091   GNUNET_NETWORK_fdset_copy_native (grs, &rs, max + 1);
1092   GNUNET_NETWORK_fdset_copy_native (gws, &ws, max + 1);
1093
1094   plugin->client_perform_task =
1095       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1096                                    timeout, grs, gws,
1097                                    &client_run, plugin);
1098   GNUNET_NETWORK_fdset_destroy (gws);
1099   GNUNET_NETWORK_fdset_destroy (grs);
1100   return GNUNET_OK;
1101 }
1102
1103
1104 /**
1105  * Task performing curl operations
1106  *
1107  * @param cls plugin as closure
1108  * @param tc gnunet scheduler task context
1109  */
1110 static void
1111 client_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1112 {
1113   struct HTTP_Client_Plugin *plugin = cls;
1114   int running;
1115   long http_statuscode;
1116   CURLMcode mret;
1117
1118   GNUNET_assert (cls != NULL);
1119
1120   plugin->client_perform_task = GNUNET_SCHEDULER_NO_TASK;
1121   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1122     return;
1123
1124   do
1125   {
1126     running = 0;
1127     mret = curl_multi_perform (plugin->curl_multi_handle, &running);
1128
1129     CURLMsg *msg;
1130     int msgs_left;
1131
1132     while ((msg = curl_multi_info_read (plugin->curl_multi_handle, &msgs_left)))
1133     {
1134       CURL *easy_h = msg->easy_handle;
1135       struct Session *s = NULL;
1136       char *d = (char *) s;
1137
1138       if (easy_h == NULL)
1139       {
1140         GNUNET_break (0);
1141         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1142                          "Client: connection to ended with reason %i: `%s', %i handles running\n",
1143                          msg->data.result,
1144                          curl_easy_strerror (msg->data.result), running);
1145         continue;
1146       }
1147
1148       GNUNET_assert (CURLE_OK ==
1149                      curl_easy_getinfo (easy_h, CURLINFO_PRIVATE, &d));
1150       s = (struct Session *) d;
1151
1152       if (GNUNET_YES != client_exist_session(plugin, s))
1153       {
1154         GNUNET_break (0);
1155         return;
1156       }
1157
1158       GNUNET_assert (s != NULL);
1159       if (msg->msg == CURLMSG_DONE)
1160       {
1161         curl_easy_getinfo (easy_h, CURLINFO_RESPONSE_CODE, &http_statuscode);
1162         if (easy_h == s->client_put)
1163         {
1164             if  ((0 != msg->data.result) || (http_statuscode != 200))
1165             {
1166                 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1167                   "Session %p/connection %p: PUT connection to `%s' ended with status %i reason %i: `%s'\n",
1168                   s, msg->easy_handle, GNUNET_i2s (&s->target),
1169                   http_statuscode,
1170                   msg->data.result,
1171                   curl_easy_strerror (msg->data.result));
1172             }
1173             else
1174               GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1175                 "Session %p/connection %p: PUT connection to `%s' ended normal\n",
1176                 s, msg->easy_handle, GNUNET_i2s (&s->target));
1177             if (s->client_get == NULL)
1178             {
1179               /* Disconnect other transmission direction and tell transport */
1180             }
1181             curl_multi_remove_handle (plugin->curl_multi_handle, easy_h);
1182             curl_easy_cleanup (easy_h);
1183             s->put_tmp_disconnecting = GNUNET_NO;
1184             s->put_tmp_disconnected = GNUNET_YES;
1185             s->client_put = NULL;
1186             s->put.easyhandle = NULL;
1187             s->put.s = NULL;
1188
1189             /*
1190              * Handling a rare case:
1191              * plugin_send was called during temporary put disconnect,
1192              * reconnect required after connection was disconnected
1193              */
1194             if (GNUNET_YES == s->put_reconnect_required)
1195             {
1196                 s->put_reconnect_required = GNUNET_NO;
1197                 if (GNUNET_SYSERR == client_connect_put(s))
1198                 {
1199                     GNUNET_break (s->client_put == NULL);
1200                     GNUNET_break (s->put_tmp_disconnected == GNUNET_NO);
1201                 }
1202             }
1203         }
1204         if (easy_h == s->client_get)
1205         {
1206             if  ((0 != msg->data.result) || (http_statuscode != 200))
1207             {
1208               GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1209                 "Session %p/connection %p: GET connection to `%s' ended with status %i reason %i: `%s'\n",
1210                 s, msg->easy_handle, GNUNET_i2s (&s->target),
1211                 http_statuscode,
1212                 msg->data.result,
1213                 curl_easy_strerror (msg->data.result));
1214
1215             }
1216             else
1217               GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1218                 "Session %p/connection %p: GET connection to `%s' ended normal\n",
1219                 s, msg->easy_handle, GNUNET_i2s (&s->target));
1220             /* Disconnect other transmission direction and tell transport */
1221             s->get.easyhandle = NULL;
1222             s->get.s = NULL;
1223             client_disconnect (s);
1224         }
1225       }
1226     }
1227   }
1228   while (mret == CURLM_CALL_MULTI_PERFORM);
1229   client_schedule (plugin, GNUNET_NO);
1230 }
1231
1232
1233 /**
1234  * Connect GET connection for a session
1235  * 
1236  * @param s the session to connect
1237  * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1238  */
1239 static int
1240 client_connect_get (struct Session *s)
1241 {
1242
1243   CURLMcode mret;
1244   /* create get connection */
1245   s->client_get = curl_easy_init ();
1246   s->get.s = s;
1247   s->get.easyhandle = s->client_get;
1248 #if VERBOSE_CURL
1249   curl_easy_setopt (s->client_get, CURLOPT_VERBOSE, 1L);
1250   curl_easy_setopt (s->client_get, CURLOPT_DEBUGFUNCTION, &client_log);
1251   curl_easy_setopt (s->client_get, CURLOPT_DEBUGDATA, &s->get);
1252 #endif
1253 #if BUILD_HTTPS
1254   curl_easy_setopt (s->client_get, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
1255         if (HTTP_OPTIONS_VERIFY_CERTIFICATE ==
1256                         (ntohl (s->addr->options) & HTTP_OPTIONS_VERIFY_CERTIFICATE))
1257         {
1258           curl_easy_setopt (s->client_get, CURLOPT_SSL_VERIFYPEER, 1L);
1259           curl_easy_setopt (s->client_get, CURLOPT_SSL_VERIFYHOST, 2L);
1260         }
1261         else
1262         {
1263                 curl_easy_setopt (s->client_get, CURLOPT_SSL_VERIFYPEER, 0);
1264                 curl_easy_setopt (s->client_get, CURLOPT_SSL_VERIFYHOST, 0);
1265         }
1266   curl_easy_setopt (s->client_get, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
1267   curl_easy_setopt (s->client_get, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS);
1268 #else
1269   curl_easy_setopt (s->client_get, CURLOPT_PROTOCOLS, CURLPROTO_HTTP);
1270   curl_easy_setopt (s->client_get, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP);
1271 #endif
1272
1273   curl_easy_setopt (s->client_get, CURLOPT_URL, s->url);
1274   //curl_easy_setopt (s->client_get, CURLOPT_HEADERFUNCTION, &curl_get_header_cb);
1275   //curl_easy_setopt (s->client_get, CURLOPT_WRITEHEADER, ps);
1276   curl_easy_setopt (s->client_get, CURLOPT_READFUNCTION, client_send_cb);
1277   curl_easy_setopt (s->client_get, CURLOPT_READDATA, s);
1278   curl_easy_setopt (s->client_get, CURLOPT_WRITEFUNCTION, client_receive);
1279   curl_easy_setopt (s->client_get, CURLOPT_WRITEDATA, s);
1280   /* No timeout by default, timeout done with session timeout */
1281   curl_easy_setopt (s->client_get, CURLOPT_TIMEOUT, 0);
1282   curl_easy_setopt (s->client_get, CURLOPT_PRIVATE, s);
1283   curl_easy_setopt (s->client_get, CURLOPT_CONNECTTIMEOUT_MS,
1284                     (long) HTTP_CLIENT_NOT_VALIDATED_TIMEOUT.rel_value_us / 1000LL);
1285   curl_easy_setopt (s->client_get, CURLOPT_BUFFERSIZE,
1286                     2 * GNUNET_SERVER_MAX_MESSAGE_SIZE);
1287 #if CURL_TCP_NODELAY
1288   curl_easy_setopt (ps->recv_endpoint, CURLOPT_TCP_NODELAY, 1);
1289 #endif
1290   curl_easy_setopt (s->client_get, CURLOPT_FOLLOWLOCATION, 0);
1291
1292   mret = curl_multi_add_handle (s->plugin->curl_multi_handle, s->client_get);
1293   if (mret != CURLM_OK)
1294   {
1295       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, s->plugin->name,
1296                        "Session %p : Failed to add GET handle to multihandle: `%s'\n",
1297                        s, curl_multi_strerror (mret));
1298     curl_easy_cleanup (s->client_get);
1299     s->client_get = NULL;
1300     s->get.s = NULL;
1301     s->get.easyhandle = NULL;
1302     GNUNET_break (0);
1303     return GNUNET_SYSERR;
1304   }
1305
1306   return GNUNET_OK;
1307 }
1308
1309 /**
1310  * Connect a HTTP put connection 
1311  *
1312  * @param s the session to connect
1313  * @return GNUNET_SYSERR for hard failure, GNUNET_OK for ok
1314  */
1315 static int
1316 client_connect_put (struct Session *s)
1317 {
1318   CURLMcode mret;
1319   /* create put connection */
1320   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, s->plugin->name,
1321                        "Session %p : Init PUT handle \n", s);
1322   s->client_put = curl_easy_init ();
1323   s->put.s = s;
1324   s->put.easyhandle = s->client_put;
1325 #if VERBOSE_CURL
1326   curl_easy_setopt (s->client_put, CURLOPT_VERBOSE, 1L);
1327   curl_easy_setopt (s->client_put, CURLOPT_DEBUGFUNCTION, &client_log);
1328   curl_easy_setopt (s->client_put, CURLOPT_DEBUGDATA, &s->put);
1329 #endif
1330 #if BUILD_HTTPS
1331   curl_easy_setopt (s->client_put, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
1332         if (HTTP_OPTIONS_VERIFY_CERTIFICATE ==
1333                         (ntohl (s->addr->options) & HTTP_OPTIONS_VERIFY_CERTIFICATE))
1334         {
1335           curl_easy_setopt (s->client_put, CURLOPT_SSL_VERIFYPEER, 1L);
1336           curl_easy_setopt (s->client_put, CURLOPT_SSL_VERIFYHOST, 2L);
1337         }
1338         else
1339         {
1340                 curl_easy_setopt (s->client_put, CURLOPT_SSL_VERIFYPEER, 0);
1341                 curl_easy_setopt (s->client_put, CURLOPT_SSL_VERIFYHOST, 0);
1342         }
1343   curl_easy_setopt (s->client_get, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
1344   curl_easy_setopt (s->client_get, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS);
1345 #else
1346   curl_easy_setopt (s->client_get, CURLOPT_PROTOCOLS, CURLPROTO_HTTP);
1347   curl_easy_setopt (s->client_get, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP);
1348 #endif
1349   curl_easy_setopt (s->client_put, CURLOPT_URL, s->url);
1350   curl_easy_setopt (s->client_put, CURLOPT_UPLOAD, 1L);
1351   //curl_easy_setopt (s->client_put, CURLOPT_HEADERFUNCTION, &client_curl_header);
1352   //curl_easy_setopt (s->client_put, CURLOPT_WRITEHEADER, ps);
1353   curl_easy_setopt (s->client_put, CURLOPT_READFUNCTION, client_send_cb);
1354   curl_easy_setopt (s->client_put, CURLOPT_READDATA, s);
1355   curl_easy_setopt (s->client_put, CURLOPT_WRITEFUNCTION, client_receive_put);
1356   curl_easy_setopt (s->client_put, CURLOPT_WRITEDATA, s);
1357   /* No timeout by default, timeout done with session timeout */
1358   curl_easy_setopt (s->client_put, CURLOPT_TIMEOUT, 0);
1359   curl_easy_setopt (s->client_put, CURLOPT_PRIVATE, s);
1360   curl_easy_setopt (s->client_put, CURLOPT_CONNECTTIMEOUT_MS,
1361                     (long) HTTP_CLIENT_NOT_VALIDATED_TIMEOUT.rel_value_us / 1000LL);
1362   curl_easy_setopt (s->client_put, CURLOPT_BUFFERSIZE,
1363                     2 * GNUNET_SERVER_MAX_MESSAGE_SIZE);
1364 #if CURL_TCP_NODELAY
1365   curl_easy_setopt (s->client_put, CURLOPT_TCP_NODELAY, 1);
1366 #endif
1367   mret = curl_multi_add_handle (s->plugin->curl_multi_handle, s->client_put);
1368   if (mret != CURLM_OK)
1369   {
1370    GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, s->plugin->name,
1371                     "Session %p : Failed to add PUT handle to multihandle: `%s'\n",
1372                     s, curl_multi_strerror (mret));
1373     curl_easy_cleanup (s->client_put);
1374     s->client_put = NULL;
1375     s->put.easyhandle = NULL;
1376     s->put.s = NULL;
1377     s->put_tmp_disconnected = GNUNET_YES;
1378     return GNUNET_SYSERR;
1379   }
1380   s->put_tmp_disconnected = GNUNET_NO;
1381   return GNUNET_OK;
1382 }
1383
1384
1385 /**
1386  * Connect both PUT and GET connection for a session
1387  * 
1388  * @param s the session to connect
1389  * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1390  */
1391 static int
1392 client_connect (struct Session *s)
1393 {
1394
1395   struct HTTP_Client_Plugin *plugin = s->plugin;
1396   int res = GNUNET_OK;
1397
1398   /* create url */
1399   if (NULL == http_common_plugin_address_to_string (NULL, plugin->protocol, s->addr, s->addrlen))
1400   {
1401     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1402                      "Invalid address peer `%s'\n",
1403                      GNUNET_i2s (&s->target));
1404     return GNUNET_SYSERR;
1405   }
1406
1407   GNUNET_asprintf (&s->url, "%s/%s;%u",
1408       http_common_plugin_address_to_url (NULL, s->addr, s->addrlen),
1409                         GNUNET_h2s_full (&plugin->env->my_identity->hashPubKey),
1410                         plugin->last_tag);
1411
1412   plugin->last_tag++;
1413
1414   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1415                    "Initiating outbound session peer `%s' using address `%s'\n",
1416                    GNUNET_i2s (&s->target), s->url);
1417
1418   if ((GNUNET_SYSERR == client_connect_get (s)) ||
1419       (GNUNET_SYSERR == client_connect_put (s)))
1420   {
1421       GNUNET_break (0);
1422       return GNUNET_SYSERR;
1423   }
1424
1425   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1426                "Session %p: connected with connections GET %p and PUT %p\n",
1427                s, s->client_get, s->client_put);
1428
1429   /* Perform connect */
1430   plugin->cur_connections += 2;
1431   GNUNET_STATISTICS_set (plugin->env->stats,
1432       "# HTTP client connections",
1433       plugin->cur_connections,
1434       GNUNET_NO);
1435
1436   /* Re-schedule since handles have changed */
1437   if (plugin->client_perform_task != GNUNET_SCHEDULER_NO_TASK)
1438   {
1439     GNUNET_SCHEDULER_cancel (plugin->client_perform_task);
1440     plugin->client_perform_task = GNUNET_SCHEDULER_NO_TASK;
1441   }
1442   plugin->client_perform_task = GNUNET_SCHEDULER_add_now (client_run, plugin);
1443   return res;
1444 }
1445
1446
1447 /**
1448  * Function obtain the network type for a session
1449  *
1450  * @param cls closure ('struct Plugin*')
1451  * @param session the session
1452  * @return the network type in HBO or GNUNET_SYSERR
1453  */
1454 static enum GNUNET_ATS_Network_Type
1455 http_client_get_network (void *cls,
1456                          struct Session *session)
1457 {
1458   GNUNET_assert (NULL != session);
1459   return ntohl (session->ats_address_network_type);
1460 }
1461
1462
1463 /**
1464  * Creates a new outbound session the transport service will use to send data to the
1465  * peer
1466  *
1467  * @param cls the plugin
1468  * @param address the address
1469  * @return the session or NULL of max connections exceeded
1470  */
1471 static struct Session *
1472 http_client_plugin_get_session (void *cls,
1473                   const struct GNUNET_HELLO_Address *address)
1474 {
1475   struct HTTP_Client_Plugin *plugin = cls;
1476   struct Session * s = NULL;
1477   struct sockaddr *sa;
1478   struct GNUNET_ATS_Information ats;
1479   size_t salen = 0;
1480   int res;
1481
1482   GNUNET_assert (plugin != NULL);
1483   GNUNET_assert (address != NULL);
1484   GNUNET_assert (address->address != NULL);
1485
1486   /* find existing session */
1487   s = client_lookup_session (plugin, address);
1488   if (s != NULL)
1489     return s;
1490
1491   if (plugin->max_connections <= plugin->cur_connections)
1492   {
1493     GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, plugin->name,
1494                      "Maximum number of connections (%u) reached: "
1495                      "cannot connect to peer `%s'\n",
1496                      plugin->max_connections,
1497                      GNUNET_i2s (&address->peer));
1498     return NULL;
1499   }
1500
1501   /* Determine network location */
1502   ats.type = htonl (GNUNET_ATS_NETWORK_TYPE);
1503   ats.value = htonl (GNUNET_ATS_NET_UNSPECIFIED);
1504   sa = http_common_socket_from_address (address->address, address->address_length, &res);
1505   if (GNUNET_SYSERR == res)
1506   {
1507       return NULL;
1508   }
1509   else if (GNUNET_YES == res)
1510   {
1511       GNUNET_assert (NULL != sa);
1512       if (AF_INET == sa->sa_family)
1513       {
1514           salen = sizeof (struct sockaddr_in);
1515       }
1516       else if (AF_INET6 == sa->sa_family)
1517       {
1518           salen = sizeof (struct sockaddr_in6);
1519       }
1520       ats = plugin->env->get_address_type (plugin->env->cls, sa, salen);
1521       //fprintf (stderr, "Address %s is in %s\n", GNUNET_a2s (sa,salen), GNUNET_ATS_print_network_type(ntohl(ats.value)));
1522       GNUNET_free (sa);
1523   }
1524
1525   else if (GNUNET_NO == res)
1526   {
1527                 /* Cannot convert to sockaddr -> is external hostname */
1528       ats.value = htonl (GNUNET_ATS_NET_WAN);
1529   }
1530
1531   if (GNUNET_ATS_NET_UNSPECIFIED == ntohl(ats.value))
1532   {
1533       GNUNET_break (0);
1534       return NULL;
1535   }
1536
1537   s = GNUNET_malloc (sizeof (struct Session));
1538   memcpy (&s->target, &address->peer, sizeof (struct GNUNET_PeerIdentity));
1539   s->plugin = plugin;
1540   s->addr = GNUNET_malloc (address->address_length);
1541   memcpy (s->addr, address->address, address->address_length);
1542   s->addrlen = address->address_length;
1543   s->ats_address_network_type = ats.value;
1544   s->put_paused = GNUNET_NO;
1545   s->put_tmp_disconnecting = GNUNET_NO;
1546   s->put_tmp_disconnected = GNUNET_NO;
1547   client_start_session_timeout (s);
1548
1549   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1550                    "Created new session %p for `%s' address `%s''\n",
1551                    s,
1552                    http_common_plugin_address_to_string (NULL, plugin->protocol, s->addr, s->addrlen),
1553                    GNUNET_i2s (&s->target));
1554
1555   /* add new session */
1556   GNUNET_CONTAINER_DLL_insert (plugin->head, plugin->tail, s);
1557
1558   /* initiate new connection */
1559   if (GNUNET_SYSERR == client_connect (s))
1560   {
1561     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
1562                      "Cannot connect to peer `%s' address `%s''\n",
1563                      http_common_plugin_address_to_string (NULL, plugin->protocol, s->addr, s->addrlen),
1564                      GNUNET_i2s (&s->target));
1565     client_delete_session (s);
1566     return NULL;
1567   }
1568   return s;
1569 }
1570
1571
1572 /**
1573  * Setup http_client plugin
1574  *
1575  * @param plugin the plugin handle
1576  * @return GNUNET_OK on success, GNUNET_SYSERR on error
1577  */
1578 static int
1579 client_start (struct HTTP_Client_Plugin *plugin)
1580 {
1581   curl_global_init (CURL_GLOBAL_ALL);
1582   plugin->curl_multi_handle = curl_multi_init ();
1583
1584   if (NULL == plugin->curl_multi_handle)
1585   {
1586     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
1587                      _("Could not initialize curl multi handle, failed to start %s plugin!\n"),
1588                      plugin->name);
1589     return GNUNET_SYSERR;
1590   }
1591   return GNUNET_OK;
1592 }
1593
1594 /**
1595  * Session was idle, so disconnect it
1596  */
1597 static void
1598 client_session_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1599 {
1600   GNUNET_assert (NULL != cls);
1601   struct Session *s = cls;
1602
1603   s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1604   GNUNET_log (TIMEOUT_LOG,
1605               "Session %p was idle for %s, disconnecting\n",
1606               s,
1607               GNUNET_STRINGS_relative_time_to_string (CLIENT_SESSION_TIMEOUT,
1608                                                       GNUNET_YES));
1609
1610   /* call session destroy function */
1611   GNUNET_assert (GNUNET_OK == client_disconnect (s));
1612 }
1613
1614
1615 /**
1616  * Start session timeout for session s
1617  *
1618  * @param s the session
1619  */
1620 static void
1621 client_start_session_timeout (struct Session *s)
1622 {
1623
1624  GNUNET_assert (NULL != s);
1625  GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == s->timeout_task);
1626  s->timeout_task =  GNUNET_SCHEDULER_add_delayed (CLIENT_SESSION_TIMEOUT,
1627                                                   &client_session_timeout,
1628                                                   s);
1629  GNUNET_log (TIMEOUT_LOG,
1630              "Timeout for session %p set to %s\n",
1631              s, 
1632              GNUNET_STRINGS_relative_time_to_string (CLIENT_SESSION_TIMEOUT,
1633                                                      GNUNET_YES));
1634 }
1635
1636
1637 /**
1638  * Increment session timeout due to activity for session s
1639  *
1640  * param s the session
1641  */
1642 static void
1643 client_reschedule_session_timeout (struct Session *s)
1644 {
1645
1646  GNUNET_assert (NULL != s);
1647  GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != s->timeout_task);
1648
1649  GNUNET_SCHEDULER_cancel (s->timeout_task);
1650  s->timeout_task =  GNUNET_SCHEDULER_add_delayed (CLIENT_SESSION_TIMEOUT,
1651                                                   &client_session_timeout,
1652                                                   s);
1653  GNUNET_log (TIMEOUT_LOG,
1654              "Timeout rescheduled for session %p set to %s\n",
1655              s,
1656              GNUNET_STRINGS_relative_time_to_string (CLIENT_SESSION_TIMEOUT,
1657                                                      GNUNET_YES));
1658 }
1659
1660
1661 /**
1662  * Cancel timeout due to activity for session s
1663  *
1664  * param s the session
1665  */
1666 static void
1667 client_stop_session_timeout (struct Session *s)
1668 {
1669  GNUNET_assert (NULL != s);
1670
1671  if (GNUNET_SCHEDULER_NO_TASK != s->timeout_task)
1672  {
1673    GNUNET_SCHEDULER_cancel (s->timeout_task);
1674    s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1675    GNUNET_log (TIMEOUT_LOG, "Timeout stopped for session %p\n", s);
1676  }
1677 }
1678
1679
1680 /**
1681  * Another peer has suggested an address for this
1682  * peer and transport plugin.  Check that this could be a valid
1683  * address.  If so, consider adding it to the list
1684  * of addresses.
1685  *
1686  * @param cls closure
1687  * @param addr pointer to the address
1688  * @param addrlen length of addr
1689  * @return GNUNET_OK if this is a plausible address for this peer
1690  *         and transport
1691  */
1692 static int
1693 http_client_plugin_address_suggested (void *cls, const void *addr, size_t addrlen)
1694 {
1695   /* struct Plugin *plugin = cls; */
1696
1697   /* A HTTP/S client does not have any valid address so:*/
1698   return GNUNET_NO;
1699 }
1700
1701
1702 /**
1703  * Exit point from the plugin.
1704  *
1705  * @param cls api as closure
1706  * @return NULL
1707  */
1708 void *
1709 LIBGNUNET_PLUGIN_TRANSPORT_DONE (void *cls)
1710 {
1711   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1712   struct HTTP_Client_Plugin *plugin = api->cls;
1713   struct Session *pos;
1714   struct Session *next;
1715
1716   if (NULL == api->cls)
1717   {
1718     /* Stub shutdown */
1719     GNUNET_free (api);
1720     return NULL;
1721   }
1722
1723   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1724                    _("Shutting down plugin `%s'\n"),
1725                    plugin->name);
1726
1727
1728   next = plugin->head;
1729   while (NULL != (pos = next))
1730   {
1731       next = pos->next;
1732       client_disconnect (pos);
1733   }
1734   if (GNUNET_SCHEDULER_NO_TASK != plugin->client_perform_task)
1735   {
1736       GNUNET_SCHEDULER_cancel (plugin->client_perform_task);
1737       plugin->client_perform_task = GNUNET_SCHEDULER_NO_TASK;
1738   }
1739
1740
1741   if (NULL != plugin->curl_multi_handle)
1742   {
1743     curl_multi_cleanup (plugin->curl_multi_handle);
1744     plugin->curl_multi_handle = NULL;
1745   }
1746   curl_global_cleanup ();
1747
1748   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1749                    _("Shutdown for plugin `%s' complete\n"),
1750                    plugin->name);
1751
1752   GNUNET_free (plugin);
1753   GNUNET_free (api);
1754   return NULL;
1755 }
1756
1757
1758 /**
1759  * Configure plugin
1760  *
1761  * @param plugin the plugin handle
1762  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
1763  */
1764 static int
1765 client_configure_plugin (struct HTTP_Client_Plugin *plugin)
1766 {
1767   unsigned long long max_connections;
1768
1769   /* Optional parameters */
1770   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (plugin->env->cfg,
1771                       plugin->name,
1772                       "MAX_CONNECTIONS", &max_connections))
1773     max_connections = 128;
1774   plugin->max_connections = max_connections;
1775
1776   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1777                    _("Maximum number of connections is %u\n"),
1778                    plugin->max_connections);
1779   return GNUNET_OK;
1780 }
1781
1782 const char *http_plugin_address_to_string (void *cls,
1783                                            const void *addr,
1784                                            size_t addrlen)
1785 {
1786         return http_common_plugin_address_to_string (cls, PLUGIN_NAME, addr, addrlen);
1787 }
1788
1789 /**
1790  * Entry point for the plugin.
1791  */
1792 void *
1793 LIBGNUNET_PLUGIN_TRANSPORT_INIT (void *cls)
1794 {
1795   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1796   struct GNUNET_TRANSPORT_PluginFunctions *api;
1797   struct HTTP_Client_Plugin *plugin;
1798
1799   if (NULL == env->receive)
1800   {
1801     /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
1802        initialze the plugin or the API */
1803     api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1804     api->cls = NULL;
1805     api->address_to_string = &http_plugin_address_to_string;
1806     api->string_to_address = &http_common_plugin_string_to_address;
1807     api->address_pretty_printer = &http_common_plugin_address_pretty_printer;
1808     return api;
1809   }
1810
1811   plugin = GNUNET_malloc (sizeof (struct HTTP_Client_Plugin));
1812   p = plugin;
1813   plugin->env = env;
1814   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1815   api->cls = plugin;
1816   api->send = &http_client_plugin_send;
1817   api->disconnect = &http_client_plugin_disconnect;
1818   api->check_address = &http_client_plugin_address_suggested;
1819   api->get_session = &http_client_plugin_get_session;
1820   api->address_to_string = &http_plugin_address_to_string;
1821   api->string_to_address = &http_common_plugin_string_to_address;
1822   api->address_pretty_printer = &http_common_plugin_address_pretty_printer;
1823   api->get_network = &http_client_get_network;
1824
1825 #if BUILD_HTTPS
1826   plugin->name = "transport-https_client";
1827   plugin->protocol = "https";
1828 #else
1829   plugin->name = "transport-http_client";
1830   plugin->protocol = "http";
1831 #endif
1832   plugin->last_tag = 1;
1833   plugin->options = 0; /* Setup options */
1834
1835   if (GNUNET_SYSERR == client_configure_plugin (plugin))
1836   {
1837       LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
1838       return NULL;
1839   }
1840
1841   /* Start client */
1842   if (GNUNET_SYSERR == client_start (plugin))
1843   {
1844       LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
1845       return NULL;
1846   }
1847   return api;
1848 }
1849
1850 /* end of plugin_transport_http_client.c */