5b219a467c1966d14332bfed33b53a625ced0f0b
[oweals/gnunet.git] / src / transport / tcp_connection_legacy.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2009-2013 GNUnet e.V.
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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20
21 /**
22  * @file util/connection.c
23  * @brief  TCP connection management
24  * @author Christian Grothoff
25  *
26  * This code is rather complex.  Only modify it if you
27  * 1) Have a NEW testcase showing that the new code
28  *    is needed and correct
29  * 2) All EXISTING testcases pass with the new code
30  * These rules should apply in general, but for this
31  * module they are VERY, VERY important.
32  */
33 #include "platform.h"
34 #include "gnunet_util_lib.h"
35 #include "gnunet_resolver_service.h"
36
37
38 /**
39  * Timeout we use on TCP connect before trying another
40  * result from the DNS resolver.  Actual value used
41  * is this value divided by the number of address families.
42  * Default is 5s.
43  */
44 #define CONNECT_RETRY_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
45
46
47
48 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util-connection", syscall)
49
50
51 /**
52  * Transmission handle.  There can only be one for each connection.
53  */
54 struct GNUNET_CONNECTION_TransmitHandle
55 {
56
57   /**
58    * Function to call if the send buffer has notify_size
59    * bytes available.
60    */
61   GNUNET_CONNECTION_TransmitReadyNotify notify_ready;
62
63   /**
64    * Closure for notify_ready.
65    */
66   void *notify_ready_cls;
67
68   /**
69    * Our connection handle.
70    */
71   struct GNUNET_CONNECTION_Handle *connection;
72
73   /**
74    * Timeout for receiving (in absolute time).
75    */
76   struct GNUNET_TIME_Absolute transmit_timeout;
77
78   /**
79    * Task called on timeout.
80    */
81   struct GNUNET_SCHEDULER_Task * timeout_task;
82
83   /**
84    * At what number of bytes available in the
85    * write buffer should the notify method be called?
86    */
87   size_t notify_size;
88
89 };
90
91
92 /**
93  * During connect, we try multiple possible IP addresses
94  * to find out which one might work.
95  */
96 struct AddressProbe
97 {
98
99   /**
100    * This is a linked list.
101    */
102   struct AddressProbe *next;
103
104   /**
105    * This is a doubly-linked list.
106    */
107   struct AddressProbe *prev;
108
109   /**
110    * The address; do not free (allocated at the end of this struct).
111    */
112   const struct sockaddr *addr;
113
114   /**
115    * Underlying OS's socket.
116    */
117   struct GNUNET_NETWORK_Handle *sock;
118
119   /**
120    * Connection for which we are probing.
121    */
122   struct GNUNET_CONNECTION_Handle *connection;
123
124   /**
125    * Lenth of addr.
126    */
127   socklen_t addrlen;
128
129   /**
130    * Task waiting for the connection to finish connecting.
131    */
132   struct GNUNET_SCHEDULER_Task * task;
133 };
134
135
136 /**
137  * @brief handle for a network connection
138  */
139 struct GNUNET_CONNECTION_Handle
140 {
141
142   /**
143    * Configuration to use.
144    */
145   const struct GNUNET_CONFIGURATION_Handle *cfg;
146
147   /**
148    * Linked list of sockets we are currently trying out
149    * (during connect).
150    */
151   struct AddressProbe *ap_head;
152
153   /**
154    * Linked list of sockets we are currently trying out
155    * (during connect).
156    */
157   struct AddressProbe *ap_tail;
158
159   /**
160    * Network address of the other end-point, may be NULL.
161    */
162   struct sockaddr *addr;
163
164   /**
165    * Pointer to the hostname if connection was
166    * created using DNS lookup, otherwise NULL.
167    */
168   char *hostname;
169
170   /**
171    * Underlying OS's socket, set to NULL after fatal errors.
172    */
173   struct GNUNET_NETWORK_Handle *sock;
174
175   /**
176    * Function to call on data received, NULL if no receive is pending.
177    */
178   GNUNET_CONNECTION_Receiver receiver;
179
180   /**
181    * Closure for @e receiver.
182    */
183   void *receiver_cls;
184
185   /**
186    * Pointer to our write buffer.
187    */
188   char *write_buffer;
189
190   /**
191    * Current size of our @e write_buffer.
192    */
193   size_t write_buffer_size;
194
195   /**
196    * Current write-offset in @e write_buffer (where
197    * would we write next).
198    */
199   size_t write_buffer_off;
200
201   /**
202    * Current read-offset in @e write_buffer (how many
203    * bytes have already been sent).
204    */
205   size_t write_buffer_pos;
206
207   /**
208    * Length of @e addr.
209    */
210   socklen_t addrlen;
211
212   /**
213    * Read task that we may need to wait for.
214    */
215   struct GNUNET_SCHEDULER_Task *read_task;
216
217   /**
218    * Write task that we may need to wait for.
219    */
220   struct GNUNET_SCHEDULER_Task *write_task;
221
222   /**
223    * Handle to a pending DNS lookup request.
224    */
225   struct GNUNET_RESOLVER_RequestHandle *dns_active;
226
227   /**
228    * The handle we return for #GNUNET_CONNECTION_notify_transmit_ready().
229    */
230   struct GNUNET_CONNECTION_TransmitHandle nth;
231
232   /**
233    * Timeout for receiving (in absolute time).
234    */
235   struct GNUNET_TIME_Absolute receive_timeout;
236
237   /**
238    * Maximum number of bytes to read (for receiving).
239    */
240   size_t max;
241
242   /**
243    * Port to connect to.
244    */
245   uint16_t port;
246
247   /**
248    * When shutdown, do not ever actually close the socket, but
249    * free resources.  Only should ever be set if using program
250    * termination as a signal (because only then will the leaked
251    * socket be freed!)
252    */
253   int8_t persist;
254
255   /**
256    * Usually 0.  Set to 1 if this handle is in use, and should
257    * #GNUNET_CONNECTION_destroy() be called right now, the action needs
258    * to be deferred by setting it to -1.
259    */
260   int8_t destroy_later;
261
262   /**
263    * Handle to subsequent connection after proxy handshake completes,
264    */
265   struct GNUNET_CONNECTION_Handle *proxy_handshake;
266
267 };
268
269
270 /**
271  * Set the persist option on this connection handle.  Indicates
272  * that the underlying socket or fd should never really be closed.
273  * Used for indicating process death.
274  *
275  * @param connection the connection to set persistent
276  */
277 void
278 GNUNET_CONNECTION_persist_ (struct GNUNET_CONNECTION_Handle *connection)
279 {
280   connection->persist = GNUNET_YES;
281 }
282
283
284 /**
285  * Disable the "CORK" feature for communication with the given connection,
286  * forcing the OS to immediately flush the buffer on transmission
287  * instead of potentially buffering multiple messages.  Essentially
288  * reduces the OS send buffers to zero.
289  * Used to make sure that the last messages sent through the connection
290  * reach the other side before the process is terminated.
291  *
292  * @param connection the connection to make flushing and blocking
293  * @return #GNUNET_OK on success
294  */
295 int
296 GNUNET_CONNECTION_disable_corking (struct GNUNET_CONNECTION_Handle *connection)
297 {
298   return GNUNET_NETWORK_socket_disable_corking (connection->sock);
299 }
300
301
302 /**
303  * Create a connection handle by boxing an existing OS socket.  The OS
304  * socket should henceforth be no longer used directly.
305  * #GNUNET_connection_destroy() will close it.
306  *
307  * @param osSocket existing socket to box
308  * @return the boxed connection handle
309  */
310 struct GNUNET_CONNECTION_Handle *
311 GNUNET_CONNECTION_create_from_existing (struct GNUNET_NETWORK_Handle *osSocket)
312 {
313   struct GNUNET_CONNECTION_Handle *connection;
314
315   connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
316   connection->write_buffer_size = GNUNET_MIN_MESSAGE_SIZE;
317   connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
318   connection->sock = osSocket;
319   return connection;
320 }
321
322
323 /**
324  * Create a connection handle by accepting on a listen socket.  This
325  * function may block if the listen socket has no connection ready.
326  *
327  * @param access_cb function to use to check if access is allowed
328  * @param access_cb_cls closure for @a access_cb
329  * @param lsock listen socket
330  * @return the connection handle, NULL on error
331  */
332 struct GNUNET_CONNECTION_Handle *
333 GNUNET_CONNECTION_create_from_accept (GNUNET_CONNECTION_AccessCheck access_cb,
334                                       void *access_cb_cls,
335                                       struct GNUNET_NETWORK_Handle *lsock)
336 {
337   struct GNUNET_CONNECTION_Handle *connection;
338   char addr[128];
339   socklen_t addrlen;
340   struct GNUNET_NETWORK_Handle *sock;
341   int aret;
342   struct sockaddr_in *v4;
343   struct sockaddr_in6 *v6;
344   struct sockaddr *sa;
345   void *uaddr;
346 #ifdef SO_PEERCRED
347   struct ucred uc;
348   socklen_t olen;
349 #endif
350   struct GNUNET_CONNECTION_Credentials *gcp;
351 #if HAVE_GETPEEREID || defined(SO_PEERCRED) || HAVE_GETPEERUCRED
352   struct GNUNET_CONNECTION_Credentials gc;
353
354   gc.uid = 0;
355   gc.gid = 0;
356 #endif
357
358   addrlen = sizeof (addr);
359   sock =
360       GNUNET_NETWORK_socket_accept (lsock,
361                                     (struct sockaddr *) &addr,
362                                     &addrlen);
363   if (NULL == sock)
364   {
365     if (EAGAIN != errno)
366       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "accept");
367     return NULL;
368   }
369   if ((addrlen > sizeof (addr)) || (addrlen < sizeof (sa_family_t)))
370   {
371     GNUNET_break (0);
372     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
373     return NULL;
374   }
375
376   sa = (struct sockaddr *) addr;
377   v6 = (struct sockaddr_in6 *) addr;
378   if ( (AF_INET6 == sa->sa_family) &&
379        (IN6_IS_ADDR_V4MAPPED (&v6->sin6_addr)) )
380   {
381     /* convert to V4 address */
382     v4 = GNUNET_new (struct sockaddr_in);
383     memset (v4, 0, sizeof (struct sockaddr_in));
384     v4->sin_family = AF_INET;
385 #if HAVE_SOCKADDR_IN_SIN_LEN
386     v4->sin_len = (u_char) sizeof (struct sockaddr_in);
387 #endif
388     GNUNET_memcpy (&v4->sin_addr,
389             &((char *) &v6->sin6_addr)[sizeof (struct in6_addr) -
390                                        sizeof (struct in_addr)],
391             sizeof (struct in_addr));
392     v4->sin_port = v6->sin6_port;
393     uaddr = v4;
394     addrlen = sizeof (struct sockaddr_in);
395   }
396   else
397   {
398     uaddr = GNUNET_malloc (addrlen);
399     GNUNET_memcpy (uaddr, addr, addrlen);
400   }
401   gcp = NULL;
402   if (AF_UNIX == sa->sa_family)
403   {
404 #if HAVE_GETPEEREID
405     /* most BSDs */
406     if (0 == getpeereid (GNUNET_NETWORK_get_fd (sock),
407                          &gc.uid,
408                          &gc.gid))
409       gcp = &gc;
410 #else
411 #ifdef SO_PEERCRED
412     /* largely traditional GNU/Linux */
413     olen = sizeof (uc);
414     if ( (0 ==
415           getsockopt (GNUNET_NETWORK_get_fd (sock),
416                       SOL_SOCKET,
417                       SO_PEERCRED,
418                       &uc,
419                       &olen)) &&
420          (olen == sizeof (uc)) )
421     {
422       gc.uid = uc.uid;
423       gc.gid = uc.gid;
424       gcp = &gc;
425     }
426 #else
427 #if HAVE_GETPEERUCRED
428     /* this is for Solaris 10 */
429     ucred_t *uc;
430
431     uc = NULL;
432     if (0 == getpeerucred (GNUNET_NETWORK_get_fd (sock), &uc))
433     {
434       gc.uid = ucred_geteuid (uc);
435       gc.gid = ucred_getegid (uc);
436       gcp = &gc;
437     }
438     ucred_free (uc);
439 #endif
440 #endif
441 #endif
442   }
443
444   if ( (NULL != access_cb) &&
445        (GNUNET_YES != (aret = access_cb (access_cb_cls,
446                                          gcp,
447                                          uaddr,
448                                          addrlen))) )
449   {
450     if (GNUNET_NO == aret)
451       LOG (GNUNET_ERROR_TYPE_INFO,
452            _("Access denied to `%s'\n"),
453            GNUNET_a2s (uaddr,
454                        addrlen));
455     GNUNET_break (GNUNET_OK ==
456                   GNUNET_NETWORK_socket_shutdown (sock,
457                                                   SHUT_RDWR));
458     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
459     GNUNET_free (uaddr);
460     return NULL;
461   }
462   connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
463   connection->write_buffer_size = GNUNET_MIN_MESSAGE_SIZE;
464   connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
465   connection->addr = uaddr;
466   connection->addrlen = addrlen;
467   connection->sock = sock;
468   LOG (GNUNET_ERROR_TYPE_INFO,
469        _("Accepting connection from `%s': %p\n"),
470        GNUNET_a2s (uaddr,
471                    addrlen),
472        connection);
473   return connection;
474 }
475
476
477 /**
478  * Obtain the network address of the other party.
479  *
480  * @param connection the client to get the address for
481  * @param addr where to store the address
482  * @param addrlen where to store the length of the @a addr
483  * @return #GNUNET_OK on success
484  */
485 int
486 GNUNET_CONNECTION_get_address (struct GNUNET_CONNECTION_Handle *connection,
487                                void **addr,
488                                size_t *addrlen)
489 {
490   if ((NULL == connection->addr) || (0 == connection->addrlen))
491     return GNUNET_NO;
492   *addr = GNUNET_malloc (connection->addrlen);
493   GNUNET_memcpy (*addr, connection->addr, connection->addrlen);
494   *addrlen = connection->addrlen;
495   return GNUNET_OK;
496 }
497
498
499 /**
500  * Tell the receiver callback that we had an IO error.
501  *
502  * @param connection connection to signal error
503  * @param errcode error code to send
504  */
505 static void
506 signal_receive_error (struct GNUNET_CONNECTION_Handle *connection,
507                       int errcode)
508 {
509   GNUNET_CONNECTION_Receiver receiver;
510
511   LOG (GNUNET_ERROR_TYPE_DEBUG,
512        "Receive encounters error (%s), connection closed (%p)\n",
513        STRERROR (errcode),
514        connection);
515   GNUNET_assert (NULL != (receiver = connection->receiver));
516   connection->receiver = NULL;
517   receiver (connection->receiver_cls,
518             NULL,
519             0,
520             connection->addr,
521             connection->addrlen,
522             errcode);
523 }
524
525
526 /**
527  * Tell the receiver callback that a timeout was reached.
528  *
529  * @param connection connection to signal for
530  */
531 static void
532 signal_receive_timeout (struct GNUNET_CONNECTION_Handle *connection)
533 {
534   GNUNET_CONNECTION_Receiver receiver;
535
536   LOG (GNUNET_ERROR_TYPE_DEBUG,
537        "Connection signals timeout to receiver (%p)!\n",
538        connection);
539   GNUNET_assert (NULL != (receiver = connection->receiver));
540   connection->receiver = NULL;
541   receiver (connection->receiver_cls, NULL, 0, NULL, 0, 0);
542 }
543
544
545 /**
546  * We failed to transmit data to the service, signal the error.
547  *
548  * @param connection handle that had trouble
549  * @param ecode error code (errno)
550  */
551 static void
552 signal_transmit_error (struct GNUNET_CONNECTION_Handle *connection,
553                        int ecode)
554 {
555   GNUNET_CONNECTION_TransmitReadyNotify notify;
556
557   LOG (GNUNET_ERROR_TYPE_DEBUG,
558        "Transmission encounterd error (%s), connection closed (%p)\n",
559        STRERROR (ecode),
560        connection);
561   if (NULL != connection->sock)
562   {
563     (void) GNUNET_NETWORK_socket_shutdown (connection->sock,
564                                            SHUT_RDWR);
565     GNUNET_break (GNUNET_OK ==
566                   GNUNET_NETWORK_socket_close (connection->sock));
567     connection->sock = NULL;
568     GNUNET_assert (NULL == connection->write_task);
569   }
570   if (NULL != connection->read_task)
571   {
572     /* send errors trigger read errors... */
573     GNUNET_SCHEDULER_cancel (connection->read_task);
574     connection->read_task = NULL;
575     signal_receive_timeout (connection);
576     return;
577   }
578   if (NULL == connection->nth.notify_ready)
579     return;                     /* nobody to tell about it */
580   notify = connection->nth.notify_ready;
581   connection->nth.notify_ready = NULL;
582   notify (connection->nth.notify_ready_cls,
583           0,
584           NULL);
585 }
586
587
588 /**
589  * We've failed for good to establish a connection (timeout or
590  * no more addresses to try).
591  *
592  * @param connection the connection we tried to establish
593  */
594 static void
595 connect_fail_continuation (struct GNUNET_CONNECTION_Handle *connection)
596 {
597   LOG (GNUNET_ERROR_TYPE_INFO,
598        "Failed to establish TCP connection to `%s:%u', no further addresses to try.\n",
599        connection->hostname,
600     connection->port);
601   GNUNET_break (NULL == connection->ap_head);
602   GNUNET_break (NULL == connection->ap_tail);
603   GNUNET_break (GNUNET_NO == connection->dns_active);
604   GNUNET_break (NULL == connection->sock);
605   GNUNET_assert (NULL == connection->write_task);
606   GNUNET_assert (NULL == connection->proxy_handshake);
607
608   /* signal errors for jobs that used to wait on the connection */
609   connection->destroy_later = 1;
610   if (NULL != connection->receiver)
611     signal_receive_error (connection,
612                           ECONNREFUSED);
613   if (NULL != connection->nth.notify_ready)
614   {
615     GNUNET_assert (NULL != connection->nth.timeout_task);
616     GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
617     connection->nth.timeout_task = NULL;
618     signal_transmit_error (connection,
619                            ECONNREFUSED);
620   }
621   if (-1 == connection->destroy_later)
622   {
623     /* do it now */
624     connection->destroy_later = 0;
625     GNUNET_CONNECTION_destroy (connection);
626     return;
627   }
628   connection->destroy_later = 0;
629 }
630
631
632 /**
633  * We are ready to transmit (or got a timeout).
634  *
635  * @param cls our connection handle
636  */
637 static void
638 transmit_ready (void *cls);
639
640
641 /**
642  * This function is called once we either timeout or have data ready
643  * to read.
644  *
645  * @param cls connection to read from
646  */
647 static void
648 receive_ready (void *cls);
649
650
651 /**
652  * We've succeeded in establishing a connection.
653  *
654  * @param connection the connection we tried to establish
655  */
656 static void
657 connect_success_continuation (struct GNUNET_CONNECTION_Handle *connection)
658 {
659   LOG (GNUNET_ERROR_TYPE_DEBUG,
660        "Connection to `%s' succeeded! (%p)\n",
661        GNUNET_a2s (connection->addr,
662                    connection->addrlen),
663        connection);
664   /* trigger jobs that waited for the connection */
665   if (NULL != connection->receiver)
666   {
667     LOG (GNUNET_ERROR_TYPE_DEBUG,
668          "Connection succeeded, starting with receiving data (%p)\n",
669          connection);
670     GNUNET_assert (NULL == connection->read_task);
671     connection->read_task =
672       GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
673                                      (connection->receive_timeout),
674                                      connection->sock,
675                                      &receive_ready, connection);
676   }
677   if (NULL != connection->nth.notify_ready)
678   {
679     LOG (GNUNET_ERROR_TYPE_DEBUG,
680          "Connection succeeded, starting with sending data (%p)\n",
681          connection);
682     GNUNET_assert (connection->nth.timeout_task != NULL);
683     GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
684     connection->nth.timeout_task = NULL;
685     GNUNET_assert (connection->write_task == NULL);
686     connection->write_task =
687         GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
688                                         (connection->nth.transmit_timeout), connection->sock,
689                                         &transmit_ready, connection);
690   }
691 }
692
693
694 /**
695  * Scheduler let us know that we're either ready to write on the
696  * socket OR connect timed out.  Do the right thing.
697  *
698  * @param cls the `struct AddressProbe *` with the address that we are probing
699  */
700 static void
701 connect_probe_continuation (void *cls)
702 {
703   struct AddressProbe *ap = cls;
704   struct GNUNET_CONNECTION_Handle *connection = ap->connection;
705   const struct GNUNET_SCHEDULER_TaskContext *tc;
706   struct AddressProbe *pos;
707   int error;
708   socklen_t len;
709
710   GNUNET_assert (NULL != ap->sock);
711   GNUNET_CONTAINER_DLL_remove (connection->ap_head,
712                                connection->ap_tail,
713                                ap);
714   len = sizeof (error);
715   errno = 0;
716   error = 0;
717   tc = GNUNET_SCHEDULER_get_task_context ();
718   if ( (0 == (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) ||
719        (GNUNET_OK !=
720         GNUNET_NETWORK_socket_getsockopt (ap->sock,
721                                           SOL_SOCKET,
722                                           SO_ERROR,
723                                           &error,
724                                           &len)) ||
725        (0 != error) )
726   {
727     GNUNET_break (GNUNET_OK ==
728                   GNUNET_NETWORK_socket_close (ap->sock));
729     GNUNET_free (ap);
730     if ( (NULL == connection->ap_head) &&
731          (GNUNET_NO == connection->dns_active) &&
732          (NULL == connection->proxy_handshake) )
733       connect_fail_continuation (connection);
734     return;
735   }
736   GNUNET_assert (NULL == connection->sock);
737   connection->sock = ap->sock;
738   GNUNET_assert (NULL == connection->addr);
739   connection->addr = GNUNET_malloc (ap->addrlen);
740   GNUNET_memcpy (connection->addr, ap->addr, ap->addrlen);
741   connection->addrlen = ap->addrlen;
742   GNUNET_free (ap);
743   /* cancel all other attempts */
744   while (NULL != (pos = connection->ap_head))
745   {
746     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
747     GNUNET_SCHEDULER_cancel (pos->task);
748     GNUNET_CONTAINER_DLL_remove (connection->ap_head,
749                                  connection->ap_tail,
750                                  pos);
751     GNUNET_free (pos);
752   }
753   connect_success_continuation (connection);
754 }
755
756
757 /**
758  * Try to establish a connection given the specified address.
759  * This function is called by the resolver once we have a DNS reply.
760  *
761  * @param cls our `struct GNUNET_CONNECTION_Handle *`
762  * @param addr address to try, NULL for "last call"
763  * @param addrlen length of @a addr
764  */
765 static void
766 try_connect_using_address (void *cls,
767                            const struct sockaddr *addr,
768                            socklen_t addrlen)
769 {
770   struct GNUNET_CONNECTION_Handle *connection = cls;
771   struct AddressProbe *ap;
772   struct GNUNET_TIME_Relative delay;
773
774   if (NULL == addr)
775   {
776     connection->dns_active = NULL;
777     if ((NULL == connection->ap_head) &&
778         (NULL == connection->sock) &&
779         (NULL == connection->proxy_handshake))
780       connect_fail_continuation (connection);
781     return;
782   }
783   if (NULL != connection->sock)
784     return;                     /* already connected */
785   GNUNET_assert (NULL == connection->addr);
786   /* try to connect */
787   LOG (GNUNET_ERROR_TYPE_DEBUG,
788        "Trying to connect using address `%s:%u/%s:%u'\n",
789        connection->hostname,
790        connection->port,
791        GNUNET_a2s (addr, addrlen),
792        connection->port);
793   ap = GNUNET_malloc (sizeof (struct AddressProbe) + addrlen);
794   ap->addr = (const struct sockaddr *) &ap[1];
795   GNUNET_memcpy (&ap[1], addr, addrlen);
796   ap->addrlen = addrlen;
797   ap->connection = connection;
798
799   switch (ap->addr->sa_family)
800   {
801   case AF_INET:
802     ((struct sockaddr_in *) ap->addr)->sin_port = htons (connection->port);
803     break;
804   case AF_INET6:
805     ((struct sockaddr_in6 *) ap->addr)->sin6_port = htons (connection->port);
806     break;
807   default:
808     GNUNET_break (0);
809     GNUNET_free (ap);
810     return;                     /* not supported by us */
811   }
812   ap->sock = GNUNET_NETWORK_socket_create (ap->addr->sa_family,
813                                            SOCK_STREAM, 0);
814   if (NULL == ap->sock)
815   {
816     GNUNET_free (ap);
817     return;                     /* not supported by OS */
818   }
819   LOG (GNUNET_ERROR_TYPE_INFO,
820        "Trying to connect to `%s' (%p)\n",
821        GNUNET_a2s (ap->addr, ap->addrlen),
822        connection);
823   if ((GNUNET_OK !=
824        GNUNET_NETWORK_socket_connect (ap->sock,
825                                       ap->addr,
826                                       ap->addrlen)) &&
827       (EINPROGRESS != errno))
828   {
829     /* maybe refused / unsupported address, try next */
830     LOG_STRERROR (GNUNET_ERROR_TYPE_INFO, "connect");
831     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (ap->sock));
832     GNUNET_free (ap);
833     return;
834   }
835   GNUNET_CONTAINER_DLL_insert (connection->ap_head, connection->ap_tail, ap);
836   delay = CONNECT_RETRY_TIMEOUT;
837   if (NULL != connection->nth.notify_ready)
838     delay = GNUNET_TIME_relative_min (delay,
839                                       GNUNET_TIME_absolute_get_remaining (connection->nth.transmit_timeout));
840   if (NULL != connection->receiver)
841     delay = GNUNET_TIME_relative_min (delay,
842                                       GNUNET_TIME_absolute_get_remaining (connection->receive_timeout));
843   ap->task = GNUNET_SCHEDULER_add_write_net (delay,
844                                              ap->sock,
845                                              &connect_probe_continuation,
846                                              ap);
847 }
848
849
850 /**
851  * Create a connection handle by (asynchronously) connecting to a host.
852  * This function returns immediately, even if the connection has not
853  * yet been established.  This function only creates TCP connections.
854  *
855  * @param cfg configuration to use
856  * @param hostname name of the host to connect to
857  * @param port port to connect to
858  * @return the connection handle
859  */
860 struct GNUNET_CONNECTION_Handle *
861 GNUNET_CONNECTION_create_from_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
862                                        const char *hostname,
863                                        uint16_t port)
864 {
865   struct GNUNET_CONNECTION_Handle *connection;
866
867   GNUNET_assert (0 < strlen (hostname));        /* sanity check */
868   connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
869   connection->cfg = cfg;
870   connection->write_buffer_size = GNUNET_MIN_MESSAGE_SIZE;
871   connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
872   connection->port = port;
873   connection->hostname = GNUNET_strdup (hostname);
874   connection->dns_active =
875       GNUNET_RESOLVER_ip_get (connection->hostname,
876                               AF_UNSPEC,
877                               CONNECT_RETRY_TIMEOUT,
878                               &try_connect_using_address,
879                               connection);
880   return connection;
881 }
882
883
884 /**
885  * Create a connection handle by connecting to a UNIX domain service.
886  * This function returns immediately, even if the connection has not
887  * yet been established.  This function only creates UNIX connections.
888  *
889  * @param cfg configuration to use
890  * @param unixpath path to connect to
891  * @return the connection handle, NULL on systems without UNIX support
892  */
893 struct GNUNET_CONNECTION_Handle *
894 GNUNET_CONNECTION_create_from_connect_to_unixpath (const struct GNUNET_CONFIGURATION_Handle *cfg,
895                                                    const char *unixpath)
896 {
897 #ifdef AF_UNIX
898   struct GNUNET_CONNECTION_Handle *connection;
899   struct sockaddr_un *un;
900
901   GNUNET_assert (0 < strlen (unixpath));        /* sanity check */
902   un = GNUNET_new (struct sockaddr_un);
903   un->sun_family = AF_UNIX;
904   strncpy (un->sun_path, unixpath, sizeof (un->sun_path) - 1);
905 #ifdef LINUX
906   {
907     int abstract;
908
909     abstract = GNUNET_CONFIGURATION_get_value_yesno (cfg,
910                                                      "TESTING",
911                                                      "USE_ABSTRACT_SOCKETS");
912     if (GNUNET_YES == abstract)
913       un->sun_path[0] = '\0';
914   }
915 #endif
916 #if HAVE_SOCKADDR_UN_SUN_LEN
917   un->sun_len = (u_char) sizeof (struct sockaddr_un);
918 #endif
919   connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
920   connection->cfg = cfg;
921   connection->write_buffer_size = GNUNET_MIN_MESSAGE_SIZE;
922   connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
923   connection->port = 0;
924   connection->hostname = NULL;
925   connection->addr = (struct sockaddr *) un;
926   connection->addrlen = sizeof (struct sockaddr_un);
927   connection->sock = GNUNET_NETWORK_socket_create (AF_UNIX,
928                                                    SOCK_STREAM,
929                                                    0);
930   if (NULL == connection->sock)
931   {
932     GNUNET_free (connection->addr);
933     GNUNET_free (connection->write_buffer);
934     GNUNET_free (connection);
935     return NULL;
936   }
937   if ( (GNUNET_OK !=
938         GNUNET_NETWORK_socket_connect (connection->sock,
939                                        connection->addr,
940                                        connection->addrlen)) &&
941        (EINPROGRESS != errno) )
942   {
943     /* Just return; we expect everything to work eventually so don't fail HARD */
944     GNUNET_break (GNUNET_OK ==
945                   GNUNET_NETWORK_socket_close (connection->sock));
946     connection->sock = NULL;
947     return connection;
948   }
949   connect_success_continuation (connection);
950   return connection;
951 #else
952   return NULL;
953 #endif
954 }
955
956
957 /**
958  * Create a connection handle by (asynchronously) connecting to a host.
959  * This function returns immediately, even if the connection has not
960  * yet been established.  This function only creates TCP connections.
961  *
962  * @param s socket to connect
963  * @param serv_addr server address
964  * @param addrlen length of @a serv_addr
965  * @return the connection handle
966  */
967 struct GNUNET_CONNECTION_Handle *
968 GNUNET_CONNECTION_connect_socket (struct GNUNET_NETWORK_Handle *s,
969                                   const struct sockaddr *serv_addr,
970                                   socklen_t addrlen)
971 {
972   struct GNUNET_CONNECTION_Handle *connection;
973
974   if ( (GNUNET_OK !=
975         GNUNET_NETWORK_socket_connect (s, serv_addr, addrlen)) &&
976        (EINPROGRESS != errno) )
977   {
978     /* maybe refused / unsupported address, try next */
979     LOG_STRERROR (GNUNET_ERROR_TYPE_DEBUG,
980                   "connect");
981     LOG (GNUNET_ERROR_TYPE_DEBUG,
982          "Attempt to connect to `%s' failed\n",
983          GNUNET_a2s (serv_addr,
984                      addrlen));
985     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (s));
986     return NULL;
987   }
988   connection = GNUNET_CONNECTION_create_from_existing (s);
989   connection->addr = GNUNET_malloc (addrlen);
990   GNUNET_memcpy (connection->addr, serv_addr, addrlen);
991   connection->addrlen = addrlen;
992   LOG (GNUNET_ERROR_TYPE_INFO,
993        "Trying to connect to `%s' (%p)\n",
994        GNUNET_a2s (serv_addr, addrlen),
995        connection);
996   return connection;
997 }
998
999
1000 /**
1001  * Create a connection handle by creating a socket and
1002  * (asynchronously) connecting to a host.  This function returns
1003  * immediately, even if the connection has not yet been established.
1004  * This function only creates TCP connections.
1005  *
1006  * @param af_family address family to use
1007  * @param serv_addr server address
1008  * @param addrlen length of @a serv_addr
1009  * @return the connection handle
1010  */
1011 struct GNUNET_CONNECTION_Handle *
1012 GNUNET_CONNECTION_create_from_sockaddr (int af_family,
1013                                         const struct sockaddr *serv_addr,
1014                                         socklen_t addrlen)
1015 {
1016   struct GNUNET_NETWORK_Handle *s;
1017
1018   s = GNUNET_NETWORK_socket_create (af_family, SOCK_STREAM, 0);
1019   if (NULL == s)
1020   {
1021     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
1022                   "socket");
1023     return NULL;
1024   }
1025   return GNUNET_CONNECTION_connect_socket (s,
1026                                            serv_addr,
1027                                            addrlen);
1028 }
1029
1030
1031 /**
1032  * Check if connection is valid (no fatal errors have happened so far).
1033  * Note that a connection that is still trying to connect is considered
1034  * valid.
1035  *
1036  * @param connection connection to check
1037  * @return #GNUNET_YES if valid, #GNUNET_NO otherwise
1038  */
1039 int
1040 GNUNET_CONNECTION_check (struct GNUNET_CONNECTION_Handle *connection)
1041 {
1042   if ((NULL != connection->ap_head) ||
1043       (NULL != connection->dns_active) ||
1044       (NULL != connection->proxy_handshake))
1045     return GNUNET_YES;          /* still trying to connect */
1046   if ( (0 != connection->destroy_later) ||
1047        (NULL == connection->sock) )
1048     return GNUNET_NO;
1049   return GNUNET_YES;
1050 }
1051
1052
1053 /**
1054  * Close the connection and free associated resources.  There must
1055  * not be any pending requests for reading or writing to the
1056  * connection at this time.
1057  *
1058  * @param connection connection to destroy
1059  */
1060 void
1061 GNUNET_CONNECTION_destroy (struct GNUNET_CONNECTION_Handle *connection)
1062 {
1063   struct AddressProbe *pos;
1064
1065   if (0 != connection->destroy_later)
1066   {
1067     connection->destroy_later = -1;
1068     return;
1069   }
1070   LOG (GNUNET_ERROR_TYPE_DEBUG,
1071        "Shutting down connection (%p)\n",
1072        connection);
1073   GNUNET_assert (NULL == connection->nth.notify_ready);
1074   GNUNET_assert (NULL == connection->receiver);
1075   if (NULL != connection->write_task)
1076   {
1077     GNUNET_SCHEDULER_cancel (connection->write_task);
1078     connection->write_task = NULL;
1079     connection->write_buffer_off = 0;
1080   }
1081   if (NULL != connection->read_task)
1082   {
1083     GNUNET_SCHEDULER_cancel (connection->read_task);
1084     connection->read_task = NULL;
1085   }
1086   if (NULL != connection->nth.timeout_task)
1087   {
1088     GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
1089     connection->nth.timeout_task = NULL;
1090   }
1091   connection->nth.notify_ready = NULL;
1092   if (NULL != connection->dns_active)
1093   {
1094     GNUNET_RESOLVER_request_cancel (connection->dns_active);
1095     connection->dns_active = NULL;
1096   }
1097   if (NULL != connection->proxy_handshake)
1098   {
1099     /* GNUNET_CONNECTION_destroy (connection->proxy_handshake); */
1100     connection->proxy_handshake->destroy_later = -1;
1101     connection->proxy_handshake = NULL;  /* Not leaked ??? */
1102   }
1103   while (NULL != (pos = connection->ap_head))
1104   {
1105     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
1106     GNUNET_SCHEDULER_cancel (pos->task);
1107     GNUNET_CONTAINER_DLL_remove (connection->ap_head,
1108                                  connection->ap_tail,
1109                                  pos);
1110     GNUNET_free (pos);
1111   }
1112   if ( (NULL != connection->sock) &&
1113        (GNUNET_YES != connection->persist) )
1114   {
1115     if ((GNUNET_OK !=
1116          GNUNET_NETWORK_socket_shutdown (connection->sock,
1117                                          SHUT_RDWR)) &&
1118         (ENOTCONN != errno) &&
1119         (ECONNRESET != errno) )
1120       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
1121                     "shutdown");
1122   }
1123   if (NULL != connection->sock)
1124   {
1125     if (GNUNET_YES != connection->persist)
1126     {
1127       GNUNET_break (GNUNET_OK ==
1128                     GNUNET_NETWORK_socket_close (connection->sock));
1129     }
1130     else
1131     {
1132       GNUNET_NETWORK_socket_free_memory_only_ (connection->sock); /* at least no memory leak (we deliberately
1133                                                                    * leak the socket in this special case) ... */
1134     }
1135   }
1136   GNUNET_free_non_null (connection->addr);
1137   GNUNET_free_non_null (connection->hostname);
1138   GNUNET_free (connection->write_buffer);
1139   GNUNET_free (connection);
1140 }
1141
1142
1143 /**
1144  * This function is called once we either timeout
1145  * or have data ready to read.
1146  *
1147  * @param cls connection to read from
1148  */
1149 static void
1150 receive_ready (void *cls)
1151 {
1152   struct GNUNET_CONNECTION_Handle *connection = cls;
1153   const struct GNUNET_SCHEDULER_TaskContext *tc;
1154   char buffer[connection->max];
1155   ssize_t ret;
1156   GNUNET_CONNECTION_Receiver receiver;
1157
1158   connection->read_task = NULL;
1159   tc = GNUNET_SCHEDULER_get_task_context ();
1160   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1161   {
1162     LOG (GNUNET_ERROR_TYPE_DEBUG,
1163          "Receive from `%s' encounters error: timeout (%s, %p)\n",
1164          GNUNET_a2s (connection->addr,
1165                      connection->addrlen),
1166          GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (connection->receive_timeout),
1167                                                  GNUNET_YES),
1168          connection);
1169     signal_receive_timeout (connection);
1170     return;
1171   }
1172   if (NULL == connection->sock)
1173   {
1174     /* connect failed for good */
1175     signal_receive_error (connection, ECONNREFUSED);
1176     return;
1177   }
1178   GNUNET_assert (GNUNET_NETWORK_fdset_isset (tc->read_ready,
1179                                              connection->sock));
1180 RETRY:
1181   ret = GNUNET_NETWORK_socket_recv (connection->sock,
1182                                     buffer,
1183                                     connection->max);
1184   if (-1 == ret)
1185   {
1186     if (EINTR == errno)
1187       goto RETRY;
1188     signal_receive_error (connection, errno);
1189     return;
1190   }
1191   LOG (GNUNET_ERROR_TYPE_DEBUG,
1192        "receive_ready read %u/%u bytes from `%s' (%p)!\n",
1193        (unsigned int) ret,
1194        connection->max,
1195        GNUNET_a2s (connection->addr,
1196                    connection->addrlen),
1197        connection);
1198   GNUNET_assert (NULL != (receiver = connection->receiver));
1199   connection->receiver = NULL;
1200   receiver (connection->receiver_cls,
1201             buffer,
1202             ret,
1203             connection->addr,
1204             connection->addrlen,
1205             0);
1206 }
1207
1208
1209 /**
1210  * Receive data from the given connection.  Note that this function
1211  * will call @a receiver asynchronously using the scheduler.  It will
1212  * "immediately" return.  Note that there MUST only be one active
1213  * receive call per connection at any given point in time (so do not
1214  * call receive again until the receiver callback has been invoked).
1215  *
1216  * @param connection connection handle
1217  * @param max maximum number of bytes to read
1218  * @param timeout maximum amount of time to wait
1219  * @param receiver function to call with received data
1220  * @param receiver_cls closure for @a receiver
1221  */
1222 void
1223 GNUNET_CONNECTION_receive (struct GNUNET_CONNECTION_Handle *connection,
1224                            size_t max,
1225                            struct GNUNET_TIME_Relative timeout,
1226                            GNUNET_CONNECTION_Receiver receiver,
1227                            void *receiver_cls)
1228 {
1229   GNUNET_assert ((NULL == connection->read_task) &&
1230                  (NULL == connection->receiver));
1231   GNUNET_assert (NULL != receiver);
1232   connection->receiver = receiver;
1233   connection->receiver_cls = receiver_cls;
1234   connection->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1235   connection->max = max;
1236   if (NULL != connection->sock)
1237   {
1238     connection->read_task =
1239       GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1240                                      (connection->receive_timeout),
1241                                      connection->sock,
1242                                      &receive_ready,
1243                                      connection);
1244     return;
1245   }
1246   if ((NULL == connection->dns_active) &&
1247       (NULL == connection->ap_head) &&
1248       (NULL == connection->proxy_handshake))
1249   {
1250     connection->receiver = NULL;
1251     receiver (receiver_cls,
1252               NULL, 0,
1253               NULL, 0,
1254               ETIMEDOUT);
1255     return;
1256   }
1257 }
1258
1259
1260 /**
1261  * Cancel receive job on the given connection.  Note that the
1262  * receiver callback must not have been called yet in order
1263  * for the cancellation to be valid.
1264  *
1265  * @param connection connection handle
1266  * @return closure of the original receiver callback closure
1267  */
1268 void *
1269 GNUNET_CONNECTION_receive_cancel (struct GNUNET_CONNECTION_Handle *connection)
1270 {
1271   if (NULL != connection->read_task)
1272   {
1273     GNUNET_assert (connection ==
1274                    GNUNET_SCHEDULER_cancel (connection->read_task));
1275     connection->read_task = NULL;
1276   }
1277   connection->receiver = NULL;
1278   return connection->receiver_cls;
1279 }
1280
1281
1282 /**
1283  * Try to call the transmit notify method (check if we do
1284  * have enough space available first)!
1285  *
1286  * @param connection connection for which we should do this processing
1287  * @return #GNUNET_YES if we were able to call notify
1288  */
1289 static int
1290 process_notify (struct GNUNET_CONNECTION_Handle *connection)
1291 {
1292   size_t used;
1293   size_t avail;
1294   size_t size;
1295   GNUNET_CONNECTION_TransmitReadyNotify notify;
1296
1297   LOG (GNUNET_ERROR_TYPE_DEBUG,
1298        "process_notify is running\n");
1299   GNUNET_assert (NULL == connection->write_task);
1300   if (NULL == (notify = connection->nth.notify_ready))
1301   {
1302     LOG (GNUNET_ERROR_TYPE_DEBUG,
1303          "No one to notify\n");
1304     return GNUNET_NO;
1305   }
1306   used = connection->write_buffer_off - connection->write_buffer_pos;
1307   avail = connection->write_buffer_size - used;
1308   size = connection->nth.notify_size;
1309   if (size > avail)
1310   {
1311     LOG (GNUNET_ERROR_TYPE_DEBUG,
1312          "Not enough buffer\n");
1313     return GNUNET_NO;
1314   }
1315   connection->nth.notify_ready = NULL;
1316   if (connection->write_buffer_size - connection->write_buffer_off < size)
1317   {
1318     /* need to compact */
1319     memmove (connection->write_buffer,
1320              &connection->write_buffer[connection->write_buffer_pos],
1321              used);
1322     connection->write_buffer_off -= connection->write_buffer_pos;
1323     connection->write_buffer_pos = 0;
1324   }
1325   avail = connection->write_buffer_size - connection->write_buffer_off;
1326   GNUNET_assert (avail >= size);
1327   size =
1328       notify (connection->nth.notify_ready_cls, avail,
1329               &connection->write_buffer[connection->write_buffer_off]);
1330   GNUNET_assert (size <= avail);
1331   if (0 != size)
1332     connection->write_buffer_off += size;
1333   return GNUNET_YES;
1334 }
1335
1336
1337 /**
1338  * Task invoked by the scheduler when a call to transmit
1339  * is timing out (we never got enough buffer space to call
1340  * the callback function before the specified timeout
1341  * expired).
1342  *
1343  * This task notifies the client about the timeout.
1344  *
1345  * @param cls the `struct GNUNET_CONNECTION_Handle`
1346  */
1347 static void
1348 transmit_timeout (void *cls)
1349 {
1350   struct GNUNET_CONNECTION_Handle *connection = cls;
1351   GNUNET_CONNECTION_TransmitReadyNotify notify;
1352
1353   connection->nth.timeout_task = NULL;
1354   LOG (GNUNET_ERROR_TYPE_DEBUG,
1355        "Transmit to `%s:%u/%s' fails, time out reached (%p).\n",
1356        connection->hostname,
1357        connection->port,
1358        GNUNET_a2s (connection->addr,
1359                    connection->addrlen),
1360        connection);
1361   notify = connection->nth.notify_ready;
1362   GNUNET_assert (NULL != notify);
1363   connection->nth.notify_ready = NULL;
1364   notify (connection->nth.notify_ready_cls,
1365           0,
1366           NULL);
1367 }
1368
1369
1370 /**
1371  * Task invoked by the scheduler when we failed to connect
1372  * at the time of being asked to transmit.
1373  *
1374  * This task notifies the client about the error.
1375  *
1376  * @param cls the `struct GNUNET_CONNECTION_Handle`
1377  */
1378 static void
1379 connect_error (void *cls)
1380 {
1381   struct GNUNET_CONNECTION_Handle *connection = cls;
1382   GNUNET_CONNECTION_TransmitReadyNotify notify;
1383
1384   LOG (GNUNET_ERROR_TYPE_DEBUG,
1385        "Transmission request of size %u fails (%s/%u), connection failed (%p).\n",
1386        connection->nth.notify_size,
1387        connection->hostname,
1388        connection->port,
1389        connection);
1390   connection->write_task = NULL;
1391   notify = connection->nth.notify_ready;
1392   connection->nth.notify_ready = NULL;
1393   notify (connection->nth.notify_ready_cls,
1394           0,
1395           NULL);
1396 }
1397
1398
1399 /**
1400  * We are ready to transmit (or got a timeout).
1401  *
1402  * @param cls our connection handle
1403  */
1404 static void
1405 transmit_ready (void *cls)
1406 {
1407   struct GNUNET_CONNECTION_Handle *connection = cls;
1408   GNUNET_CONNECTION_TransmitReadyNotify notify;
1409   const struct GNUNET_SCHEDULER_TaskContext *tc;
1410   ssize_t ret;
1411   size_t have;
1412
1413   LOG (GNUNET_ERROR_TYPE_DEBUG,
1414        "transmit_ready running (%p).\n",
1415        connection);
1416   GNUNET_assert (NULL != connection->write_task);
1417   connection->write_task = NULL;
1418   GNUNET_assert (NULL == connection->nth.timeout_task);
1419   tc = GNUNET_SCHEDULER_get_task_context ();
1420   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1421   {
1422     LOG (GNUNET_ERROR_TYPE_DEBUG,
1423          "Transmit to `%s' fails, time out reached (%p).\n",
1424          GNUNET_a2s (connection->addr,
1425                      connection->addrlen),
1426          connection);
1427     notify = connection->nth.notify_ready;
1428     GNUNET_assert (NULL != notify);
1429     connection->nth.notify_ready = NULL;
1430     notify (connection->nth.notify_ready_cls, 0, NULL);
1431     return;
1432   }
1433   GNUNET_assert (NULL != connection->sock);
1434   if (NULL == tc->write_ready)
1435   {
1436     /* special circumstances (in particular, PREREQ_DONE after
1437      * connect): not yet ready to write, but no "fatal" error either.
1438      * Hence retry.  */
1439     goto SCHEDULE_WRITE;
1440   }
1441   if (! GNUNET_NETWORK_fdset_isset (tc->write_ready,
1442                                     connection->sock))
1443   {
1444     GNUNET_assert (NULL == connection->write_task);
1445     /* special circumstances (in particular, shutdown): not yet ready
1446      * to write, but no "fatal" error either.  Hence retry.  */
1447     goto SCHEDULE_WRITE;
1448   }
1449   GNUNET_assert (connection->write_buffer_off >= connection->write_buffer_pos);
1450   if ((NULL != connection->nth.notify_ready) &&
1451       (connection->write_buffer_size < connection->nth.notify_size))
1452   {
1453     connection->write_buffer =
1454         GNUNET_realloc (connection->write_buffer, connection->nth.notify_size);
1455     connection->write_buffer_size = connection->nth.notify_size;
1456   }
1457   process_notify (connection);
1458   have = connection->write_buffer_off - connection->write_buffer_pos;
1459   if (0 == have)
1460   {
1461     /* no data ready for writing, terminate write loop */
1462     return;
1463   }
1464   GNUNET_assert (have <= connection->write_buffer_size);
1465   GNUNET_assert (have + connection->write_buffer_pos <= connection->write_buffer_size);
1466   GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1467 RETRY:
1468   ret =
1469       GNUNET_NETWORK_socket_send (connection->sock,
1470                                   &connection->write_buffer[connection->write_buffer_pos],
1471                                   have);
1472   if (-1 == ret)
1473   {
1474     if (EINTR == errno)
1475       goto RETRY;
1476     if (NULL != connection->write_task)
1477     {
1478       GNUNET_SCHEDULER_cancel (connection->write_task);
1479       connection->write_task = NULL;
1480     }
1481     signal_transmit_error (connection, errno);
1482     return;
1483   }
1484   LOG (GNUNET_ERROR_TYPE_DEBUG,
1485        "Connection transmitted %u/%u bytes to `%s' (%p)\n",
1486        (unsigned int) ret,
1487        have,
1488        GNUNET_a2s (connection->addr,
1489                    connection->addrlen),
1490        connection);
1491   connection->write_buffer_pos += ret;
1492   if (connection->write_buffer_pos == connection->write_buffer_off)
1493   {
1494     /* transmitted all pending data */
1495     connection->write_buffer_pos = 0;
1496     connection->write_buffer_off = 0;
1497   }
1498   if ( (0 == connection->write_buffer_off) &&
1499        (NULL == connection->nth.notify_ready) )
1500     return;                     /* all data sent! */
1501   /* not done writing, schedule more */
1502 SCHEDULE_WRITE:
1503   LOG (GNUNET_ERROR_TYPE_DEBUG,
1504        "Re-scheduling transmit_ready (more to do) (%p).\n",
1505        connection);
1506   have = connection->write_buffer_off - connection->write_buffer_pos;
1507   GNUNET_assert ( (NULL != connection->nth.notify_ready) ||
1508                   (have > 0) );
1509   if (NULL == connection->write_task)
1510     connection->write_task =
1511         GNUNET_SCHEDULER_add_write_net ((connection->nth.notify_ready ==
1512                                          NULL) ? GNUNET_TIME_UNIT_FOREVER_REL :
1513                                         GNUNET_TIME_absolute_get_remaining
1514                                         (connection->nth.transmit_timeout),
1515                                         connection->sock,
1516                                         &transmit_ready, connection);
1517 }
1518
1519
1520 /**
1521  * Ask the connection to call us once the specified number of bytes
1522  * are free in the transmission buffer.  Will never call the @a notify
1523  * callback in this task, but always first go into the scheduler.
1524  *
1525  * @param connection connection
1526  * @param size number of bytes to send
1527  * @param timeout after how long should we give up (and call
1528  *        @a notify with buf NULL and size 0)?
1529  * @param notify function to call
1530  * @param notify_cls closure for @a notify
1531  * @return non-NULL if the notify callback was queued,
1532  *         NULL if we are already going to notify someone else (busy)
1533  */
1534 struct GNUNET_CONNECTION_TransmitHandle *
1535 GNUNET_CONNECTION_notify_transmit_ready (struct GNUNET_CONNECTION_Handle *connection,
1536                                          size_t size,
1537                                          struct GNUNET_TIME_Relative timeout,
1538                                          GNUNET_CONNECTION_TransmitReadyNotify notify,
1539                                          void *notify_cls)
1540 {
1541   if (NULL != connection->nth.notify_ready)
1542   {
1543     GNUNET_assert (0);
1544     return NULL;
1545   }
1546   GNUNET_assert (NULL != notify);
1547   GNUNET_assert (size < GNUNET_MAX_MESSAGE_SIZE);
1548   GNUNET_assert (connection->write_buffer_off <= connection->write_buffer_size);
1549   GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1550   GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_off);
1551   connection->nth.notify_ready = notify;
1552   connection->nth.notify_ready_cls = notify_cls;
1553   connection->nth.connection = connection;
1554   connection->nth.notify_size = size;
1555   connection->nth.transmit_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1556   GNUNET_assert (NULL == connection->nth.timeout_task);
1557   if ((NULL == connection->sock) &&
1558       (NULL == connection->ap_head) &&
1559       (NULL == connection->dns_active) &&
1560       (NULL == connection->proxy_handshake))
1561   {
1562     if (NULL != connection->write_task)
1563       GNUNET_SCHEDULER_cancel (connection->write_task);
1564     connection->write_task = GNUNET_SCHEDULER_add_now (&connect_error,
1565                                                        connection);
1566     return &connection->nth;
1567   }
1568   if (NULL != connection->write_task)
1569     return &connection->nth; /* previous transmission still in progress */
1570   if (NULL != connection->sock)
1571   {
1572     /* connected, try to transmit now */
1573     LOG (GNUNET_ERROR_TYPE_DEBUG,
1574          "Scheduling transmission (%p).\n",
1575          connection);
1576     connection->write_task =
1577         GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
1578                                         (connection->nth.transmit_timeout),
1579                                         connection->sock,
1580                                         &transmit_ready, connection);
1581     return &connection->nth;
1582   }
1583   /* not yet connected, wait for connection */
1584   LOG (GNUNET_ERROR_TYPE_DEBUG,
1585        "Need to wait to schedule transmission for connection, adding timeout task (%p).\n",
1586        connection);
1587   connection->nth.timeout_task =
1588     GNUNET_SCHEDULER_add_delayed (timeout,
1589                                   &transmit_timeout,
1590                                   connection);
1591   return &connection->nth;
1592 }
1593
1594
1595 /**
1596  * Cancel the specified transmission-ready notification.
1597  *
1598  * @param th notification to cancel
1599  */
1600 void
1601 GNUNET_CONNECTION_notify_transmit_ready_cancel (struct GNUNET_CONNECTION_TransmitHandle *th)
1602 {
1603   GNUNET_assert (NULL != th->notify_ready);
1604   th->notify_ready = NULL;
1605   if (NULL != th->timeout_task)
1606   {
1607     GNUNET_SCHEDULER_cancel (th->timeout_task);
1608     th->timeout_task = NULL;
1609   }
1610   if (NULL != th->connection->write_task)
1611   {
1612     GNUNET_SCHEDULER_cancel (th->connection->write_task);
1613     th->connection->write_task = NULL;
1614   }
1615 }
1616
1617
1618 /**
1619  * Create a connection to be proxied using a given connection.
1620  *
1621  * @param cph connection to proxy server
1622  * @return connection to be proxied
1623  */
1624 struct GNUNET_CONNECTION_Handle *
1625 GNUNET_CONNECTION_create_proxied_from_handshake (struct GNUNET_CONNECTION_Handle *cph)
1626 {
1627   struct GNUNET_CONNECTION_Handle *proxied = GNUNET_CONNECTION_create_from_existing (NULL);
1628
1629   proxied->proxy_handshake = cph;
1630   return proxied;
1631 }
1632
1633
1634 /**
1635  * Activate proxied connection and destroy initial proxy handshake connection.
1636  * There must not be any pending requests for reading or writing to the
1637  * proxy hadshake connection at this time.
1638  *
1639  * @param proxied connection connection to proxy server
1640  */
1641 void
1642 GNUNET_CONNECTION_acivate_proxied (struct GNUNET_CONNECTION_Handle *proxied)
1643 {
1644   struct GNUNET_CONNECTION_Handle *cph = proxied->proxy_handshake;
1645
1646   GNUNET_assert (NULL != cph);
1647   GNUNET_assert (NULL == proxied->sock);
1648   GNUNET_assert (NULL != cph->sock);
1649   proxied->sock = cph->sock;
1650   cph->sock = NULL;
1651   GNUNET_CONNECTION_destroy (cph);
1652   connect_success_continuation (proxied);
1653 }
1654
1655
1656 /* end of connection.c */