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