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