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