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