client sending & receiving
[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 transport service plugin
24  * @author Matthias Wachs
25  */
26
27 #include "plugin_transport_http.h"
28
29 #if VERBOSE_CLIENT
30 /**
31  * Function to log curl debug messages with GNUNET_log
32  * @param curl handle
33  * @param type curl_infotype
34  * @param data data
35  * @param size size
36  * @param cls  closure
37  * @return 0
38  */
39 static int
40 client_log (CURL * curl, curl_infotype type, char *data, size_t size, void *cls)
41 {
42   if (type == CURLINFO_TEXT)
43   {
44     char text[size + 2];
45
46     memcpy (text, data, size);
47     if (text[size - 1] == '\n')
48       text[size] = '\0';
49     else
50     {
51       text[size] = '\n';
52       text[size + 1] = '\0';
53     }
54     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Client: %X - %s", cls, text);
55   }
56   return 0;
57 }
58 #endif
59
60 int
61 client_send (struct Session *s, const char *msgbuf, size_t msgbuf_size)
62 {
63   return GNUNET_OK;
64 }
65
66 /**
67  * Task performing curl operations
68  * @param cls plugin as closure
69  * @param tc gnunet scheduler task context
70  */
71 static void
72 client_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
73
74 /**
75  * Function setting up file descriptors and scheduling task to run
76  *
77  * @param  plugin plugin as closure
78  * @return GNUNET_SYSERR for hard failure, GNUNET_OK for ok
79  */
80 static int
81 client_schedule (struct Plugin *plugin)
82 {
83   fd_set rs;
84   fd_set ws;
85   fd_set es;
86   int max;
87   struct GNUNET_NETWORK_FDSet *grs;
88   struct GNUNET_NETWORK_FDSet *gws;
89   long to;
90   CURLMcode mret;
91   struct GNUNET_TIME_Relative timeout;
92
93   /* Cancel previous scheduled task */
94   if (plugin->client_perform_task!= GNUNET_SCHEDULER_NO_TASK)
95   {
96     GNUNET_SCHEDULER_cancel (plugin->client_perform_task);
97     plugin->client_perform_task = GNUNET_SCHEDULER_NO_TASK;
98   }
99
100   max = -1;
101   FD_ZERO (&rs);
102   FD_ZERO (&ws);
103   FD_ZERO (&es);
104   mret = curl_multi_fdset (plugin->client_mh, &rs, &ws, &es, &max);
105   if (mret != CURLM_OK)
106   {
107     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("%s failed at %s:%d: `%s'\n"),
108                 "curl_multi_fdset", __FILE__, __LINE__,
109                 curl_multi_strerror (mret));
110     return GNUNET_SYSERR;
111   }
112   mret = curl_multi_timeout (plugin->client_mh, &to);
113   if (to == -1)
114     timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5);
115   else
116     timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, to);
117   if (mret != CURLM_OK)
118   {
119     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("%s failed at %s:%d: `%s'\n"),
120                 "curl_multi_timeout", __FILE__, __LINE__,
121                 curl_multi_strerror (mret));
122     return GNUNET_SYSERR;
123   }
124
125   grs = GNUNET_NETWORK_fdset_create ();
126   gws = GNUNET_NETWORK_fdset_create ();
127   GNUNET_NETWORK_fdset_copy_native (grs, &rs, max + 1);
128   GNUNET_NETWORK_fdset_copy_native (gws, &ws, max + 1);
129
130   plugin->client_perform_task =
131       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
132                                    GNUNET_SCHEDULER_NO_TASK,
133                                    timeout,
134                                    grs,
135                                    gws,
136                                    &client_run,
137                                    plugin);
138   GNUNET_NETWORK_fdset_destroy (gws);
139   GNUNET_NETWORK_fdset_destroy (grs);
140   return GNUNET_OK;
141 }
142
143
144 /**
145  * Task performing curl operations
146  * @param cls plugin as closure
147  * @param tc gnunet scheduler task context
148  */
149 static void
150 client_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
151 {
152   struct Plugin *plugin = cls;
153   static unsigned int handles_last_run;
154   int running;
155   CURLMcode mret;
156
157   GNUNET_assert (cls != NULL);
158
159   plugin->client_perform_task = GNUNET_SCHEDULER_NO_TASK;
160   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
161     return;
162
163   do
164   {
165     running = 0;
166     mret = curl_multi_perform (plugin->client_mh, &running);
167
168     CURLMsg * msg;
169     int msgs_left;
170     while ((msg = curl_multi_info_read(plugin->client_mh, &msgs_left)))
171     {
172        CURL *easy_h  = msg->easy_handle;
173        struct Session *s;
174        GNUNET_assert (easy_h != NULL);
175
176        GNUNET_assert (CURLE_OK == curl_easy_getinfo(easy_h, CURLINFO_PRIVATE, &s));
177        GNUNET_assert (s != NULL);
178
179        if (msg->msg == CURLMSG_DONE)
180        {
181 #if DEBUG_HTTP
182          GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
183                    "Connection to '%s'  %s ended\n", GNUNET_i2s(&s->target), http_plugin_address_to_string(plugin, s->addr, s->addrlen));
184 #endif
185          client_disconnect(s);
186          GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,"Notifying about ended session to peer `%s' `%s'\n", GNUNET_i2s (&s->target), http_plugin_address_to_string (plugin, s->addr, s->addrlen));
187          if (s->msg_tk != NULL)
188            GNUNET_SERVER_mst_destroy (s->msg_tk);
189          notify_session_end (plugin, &s->target, s);
190        }
191     }
192
193     handles_last_run = running;
194   }
195   while (mret == CURLM_CALL_MULTI_PERFORM);
196   client_schedule (plugin);
197 }
198
199 int
200 client_disconnect (struct Session *s)
201 {
202   int res = GNUNET_OK;
203   CURLMcode mret;
204   struct Plugin *plugin = s->plugin;
205
206 #if 0
207   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
208                    "Deleting outbound PUT session to peer `%s'\n",
209                    GNUNET_i2s (&s->target));
210 #endif
211
212   if (s->client_put != NULL)
213   {
214     mret = curl_multi_remove_handle (plugin->client_mh, s->client_put);
215     if (mret != CURLM_OK)
216     {
217       curl_easy_cleanup (s->client_put);
218       res = GNUNET_SYSERR;
219       GNUNET_break (0);
220     }
221     curl_easy_cleanup (s->client_put);
222     s->client_put = NULL;
223   }
224
225 #if DEBUG_HTTP
226   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
227                    "Deleting outbound GET session to peer `%s'\n",
228                    GNUNET_i2s (&s->target));
229 #endif
230
231   if (s->client_get != NULL)
232   {
233     mret = curl_multi_remove_handle (plugin->client_mh, s->client_get);
234     if (mret != CURLM_OK)
235     {
236       curl_easy_cleanup (s->client_get);
237       res = GNUNET_SYSERR;
238       GNUNET_break (0);
239     }
240     curl_easy_cleanup (s->client_get);
241     s->client_get = NULL;
242   }
243
244   plugin->cur_connections -= 2;
245   /* Re-schedule since handles have changed */
246   if (plugin->client_perform_task != GNUNET_SCHEDULER_NO_TASK)
247   {
248     GNUNET_SCHEDULER_cancel (plugin->client_perform_task);
249     plugin->client_perform_task = GNUNET_SCHEDULER_NO_TASK;
250   }
251
252   plugin->client_perform_task = GNUNET_SCHEDULER_add_now(client_run, plugin);
253
254   return res;
255 }
256
257 static void
258 curl_receive_mst_cb (void *cls, void *client,
259                      const struct GNUNET_MessageHeader *message)
260 {
261   struct Session *s = cls;
262   struct Plugin *plugin = s->plugin;
263   struct GNUNET_TRANSPORT_ATS_Information distance[2];
264   struct GNUNET_TIME_Relative delay;
265
266   distance[0].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
267   distance[0].value = htonl (1);
268   distance[1].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
269   distance[1].value = htonl (0);
270
271   delay = plugin->env->receive (plugin->env->cls, &s->target, message, (const struct GNUNET_TRANSPORT_ATS_Information*) &distance, 2, s, s->addr, s->addrlen);
272   s->delay = GNUNET_TIME_absolute_add(GNUNET_TIME_absolute_get(), delay);
273
274   if (GNUNET_TIME_absolute_get().abs_value < s->delay.abs_value)
275   {
276 #if VERBOSE_CLIENT
277     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name, "Client: peer `%s' address `%s' next read delayed for %llu ms\n",
278                 GNUNET_i2s (&s->target), GNUNET_a2s (s->addr, s->addrlen), delay);
279 #endif
280   }
281 }
282
283 /**
284 * Callback method used with libcurl
285 * Method is called when libcurl needs to write data during sending
286 * @param stream pointer where to write data
287 * @param size size of an individual element
288 * @param nmemb count of elements that can be written to the buffer
289 * @param ptr destination pointer, passed to the libcurl handle
290 * @return bytes read from stream
291 */
292 static size_t
293 curl_receive_cb (void *stream, size_t size, size_t nmemb, void *cls)
294 {
295   struct Session *s = cls;
296   struct Plugin *plugin = s->plugin;
297
298   if (GNUNET_TIME_absolute_get().abs_value < s->delay.abs_value)
299   {
300 #if DEBUG_HTTP
301     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
302                 "Connection %X: no inbound bandwidth available! Next read was delayed for  %llu ms\n",
303                 s, GNUNET_TIME_absolute_get_difference(s->delay, GNUNET_TIME_absolute_get()).rel_value);
304 #endif
305     return 0;
306   }
307
308   if (s->msg_tk == NULL)
309       s->msg_tk = GNUNET_SERVER_mst_create (&curl_receive_mst_cb, s);
310
311   GNUNET_SERVER_mst_receive (s->msg_tk, s, stream, size * nmemb, GNUNET_NO,
312                              GNUNET_NO);
313
314 #if VERBOSE_CLIENT
315   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name, "Received %u bytes from peer `%s'\n",
316                    size * nmemb,
317                    GNUNET_i2s (&s->target));
318 #endif
319   return (size * nmemb);
320 }
321
322 /**
323  * Callback method used with libcurl
324  * Method is called when libcurl needs to read data during sending
325  * @param stream pointer where to write data
326  * @param size size of an individual element
327  * @param nmemb count of elements that can be written to the buffer
328  * @param ptr source pointer, passed to the libcurl handle
329  * @return bytes written to stream
330  */
331 static size_t
332 curl_send_cb (void *stream, size_t size, size_t nmemb, void *ptr)
333 {
334   size_t bytes_sent = 0;
335
336 #if 0
337   struct Session *ps = ptr;
338   struct HTTP_Message *msg = ps->pending_msgs_tail;
339
340   size_t len;
341
342   if (ps->send_active == GNUNET_NO)
343     return CURL_READFUNC_PAUSE;
344   if ((ps->pending_msgs_tail == NULL) && (ps->send_active == GNUNET_YES))
345   {
346 #if DEBUG_CONNECTIONS
347     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
348                 "Connection %X: No Message to send, pausing connection\n", ps);
349 #endif
350     ps->send_active = GNUNET_NO;
351     return CURL_READFUNC_PAUSE;
352   }
353
354   GNUNET_assert (msg != NULL);
355
356   /* data to send */
357   if (msg->pos < msg->size)
358   {
359     /* data fit in buffer */
360     if ((msg->size - msg->pos) <= (size * nmemb))
361     {
362       len = (msg->size - msg->pos);
363       memcpy (stream, &msg->buf[msg->pos], len);
364       msg->pos += len;
365       bytes_sent = len;
366     }
367     else
368     {
369       len = size * nmemb;
370       memcpy (stream, &msg->buf[msg->pos], len);
371       msg->pos += len;
372       bytes_sent = len;
373     }
374   }
375   /* no data to send */
376   else
377   {
378     bytes_sent = 0;
379   }
380
381   if (msg->pos == msg->size)
382   {
383 #if DEBUG_CONNECTIONS
384     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
385                 "Connection %X: Message with %u bytes sent, removing message from queue\n",
386                 ps, msg->pos);
387 #endif
388     /* Calling transmit continuation  */
389     if (NULL != ps->pending_msgs_tail->transmit_cont)
390       msg->transmit_cont (ps->pending_msgs_tail->transmit_cont_cls,
391                           &(ps->peercontext)->identity, GNUNET_OK);
392     ps->queue_length_cur -= msg->size;
393     remove_http_message (ps, msg);
394   }
395
396 #endif
397   return bytes_sent;
398 }
399
400 int
401 client_connect (struct Session *s)
402 {
403   struct Plugin *plugin = s->plugin;
404   int res = GNUNET_OK;
405   char *url;
406   CURLMcode mret;
407
408 #if VERBOSE_CLIENT
409   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
410                    "Initiating outbound session peer `%s'\n",
411                    GNUNET_i2s (&s->target));
412 #endif
413
414   s->inbound = GNUNET_NO;
415
416   plugin->last_tag++;
417   /* create url */
418   GNUNET_asprintf (&url, "%s%s;%u", http_plugin_address_to_string (plugin, s->addr, s->addrlen), GNUNET_h2s_full (&plugin->env->my_identity->hashPubKey),plugin->last_tag);
419 #if 0
420   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
421                    "URL `%s'\n",
422                    url);
423 #endif
424   /* create get connection */
425   s->client_get = curl_easy_init ();
426 #if VERBOSE_CLIENT
427   curl_easy_setopt (s->client_get, CURLOPT_VERBOSE, 1L);
428   curl_easy_setopt (s->client_get, CURLOPT_DEBUGFUNCTION, &client_log);
429   curl_easy_setopt (s->client_get, CURLOPT_DEBUGDATA, s->client_get);
430 #endif
431 #if BUILD_HTTPS
432   curl_easy_setopt (s->client_get, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
433   curl_easy_setopt (s->client_get, CURLOPT_SSL_VERIFYPEER, 0);
434   curl_easy_setopt (s->client_get, CURLOPT_SSL_VERIFYHOST, 0);
435 #endif
436   curl_easy_setopt (s->client_get, CURLOPT_URL, url);
437   //curl_easy_setopt (s->client_get, CURLOPT_HEADERFUNCTION, &curl_get_header_cb);
438   //curl_easy_setopt (s->client_get, CURLOPT_WRITEHEADER, ps);
439   curl_easy_setopt (s->client_get, CURLOPT_READFUNCTION, curl_send_cb);
440   curl_easy_setopt (s->client_get, CURLOPT_READDATA, s);
441   curl_easy_setopt (s->client_get, CURLOPT_WRITEFUNCTION, curl_receive_cb);
442   curl_easy_setopt (s->client_get, CURLOPT_WRITEDATA, s);
443   curl_easy_setopt (s->client_get, CURLOPT_TIMEOUT_MS,
444                     (long) GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value);
445   curl_easy_setopt (s->client_get, CURLOPT_PRIVATE, s);
446   curl_easy_setopt (s->client_get, CURLOPT_CONNECTTIMEOUT_MS,
447                     (long) HTTP_NOT_VALIDATED_TIMEOUT.rel_value);
448   curl_easy_setopt (s->client_get, CURLOPT_BUFFERSIZE,
449                     2 * GNUNET_SERVER_MAX_MESSAGE_SIZE);
450 #if CURL_TCP_NODELAY
451   curl_easy_setopt (ps->recv_endpoint, CURLOPT_TCP_NODELAY, 1);
452 #endif
453
454   /* create put connection */
455   s->client_put = curl_easy_init ();
456 #if VERBOSE_CLIENT
457   curl_easy_setopt (s->client_put, CURLOPT_VERBOSE, 1L);
458   curl_easy_setopt (s->client_put, CURLOPT_DEBUGFUNCTION, &client_log);
459   curl_easy_setopt (s->client_put, CURLOPT_DEBUGDATA, s->client_put);
460 #endif
461 #if BUILD_HTTPS
462   curl_easy_setopt (s->client_put, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
463   curl_easy_setopt (s->client_put, CURLOPT_SSL_VERIFYPEER, 0);
464   curl_easy_setopt (s->client_put, CURLOPT_SSL_VERIFYHOST, 0);
465 #endif
466   curl_easy_setopt (s->client_put, CURLOPT_URL, url);
467   curl_easy_setopt (s->client_put, CURLOPT_PUT, 1L);
468   //curl_easy_setopt (s->client_put, CURLOPT_HEADERFUNCTION, &curl_put_header_cb);
469   //curl_easy_setopt (s->client_put, CURLOPT_WRITEHEADER, ps);
470   curl_easy_setopt (s->client_put, CURLOPT_READFUNCTION, curl_send_cb);
471   curl_easy_setopt (s->client_put, CURLOPT_READDATA, s);
472   curl_easy_setopt (s->client_put, CURLOPT_WRITEFUNCTION, curl_receive_cb);
473   curl_easy_setopt (s->client_put, CURLOPT_WRITEDATA, s);
474   curl_easy_setopt (s->client_put, CURLOPT_TIMEOUT_MS,
475                     (long) GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value);
476   curl_easy_setopt (s->client_put, CURLOPT_PRIVATE, s);
477   curl_easy_setopt (s->client_put, CURLOPT_CONNECTTIMEOUT_MS,
478                     (long) HTTP_NOT_VALIDATED_TIMEOUT.rel_value);
479   curl_easy_setopt (s->client_put, CURLOPT_BUFFERSIZE,
480                     2 * GNUNET_SERVER_MAX_MESSAGE_SIZE);
481 #if CURL_TCP_NODELAY
482   curl_easy_setopt (s->client_put, CURLOPT_TCP_NODELAY, 1);
483 #endif
484
485   GNUNET_free (url);
486
487   mret = curl_multi_add_handle (plugin->client_mh, s->client_get);
488   if (mret != CURLM_OK)
489   {
490     curl_easy_cleanup (s->client_get);
491     res = GNUNET_SYSERR;
492     GNUNET_break (0);
493   }
494
495   mret = curl_multi_add_handle (plugin->client_mh, s->client_put);
496   if (mret != CURLM_OK)
497   {
498     curl_multi_remove_handle (plugin->client_mh, s->client_get);
499     curl_easy_cleanup (s->client_get);
500     curl_easy_cleanup (s->client_put);
501     res = GNUNET_SYSERR;
502     GNUNET_break (0);
503   }
504
505   /* Perform connect */
506   plugin->cur_connections += 2;
507
508   /* Re-schedule since handles have changed */
509   if (plugin->client_perform_task!= GNUNET_SCHEDULER_NO_TASK)
510   {
511     GNUNET_SCHEDULER_cancel (plugin->client_perform_task);
512     plugin->client_perform_task = GNUNET_SCHEDULER_NO_TASK;
513   }
514   plugin->client_perform_task = GNUNET_SCHEDULER_add_now (client_run, plugin);
515
516   return res;
517 }
518
519 int
520 client_start (struct Plugin *plugin)
521 {
522   int res = GNUNET_OK;
523
524   curl_global_init (CURL_GLOBAL_ALL);
525   plugin->client_mh = curl_multi_init ();
526
527   if (NULL == plugin->client_mh)
528   {
529     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
530                      _
531                      ("Could not initialize curl multi handle, failed to start %s plugin!\n"),
532                      plugin->name);
533     res = GNUNET_SYSERR;
534   }
535   return res;
536 }
537
538 void
539 client_stop (struct Plugin *plugin)
540 {
541   if (plugin->client_perform_task != GNUNET_SCHEDULER_NO_TASK)
542   {
543     GNUNET_SCHEDULER_cancel (plugin->client_perform_task);
544     plugin->client_perform_task = GNUNET_SCHEDULER_NO_TASK;
545   }
546
547   curl_multi_cleanup (plugin->client_mh);
548   curl_global_cleanup ();
549 }
550
551
552
553 /* end of plugin_transport_http_client.c */