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