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