- refactor kx sending, unify under send_kx
[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 use, 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   if ( (0 != connection->destroy_later) ||
988        (NULL == connection->sock) )
989     return GNUNET_NO;
990   return GNUNET_YES;
991 }
992
993
994 /**
995  * Close the connection and free associated resources.  There must
996  * not be any pending requests for reading or writing to the
997  * connection at this time.
998  *
999  * @param connection connection to destroy
1000  */
1001 void
1002 GNUNET_CONNECTION_destroy (struct GNUNET_CONNECTION_Handle *connection)
1003 {
1004   struct AddressProbe *pos;
1005
1006   if (0 != connection->destroy_later)
1007   {
1008     connection->destroy_later = -1;
1009     return;
1010   }
1011   LOG (GNUNET_ERROR_TYPE_DEBUG,
1012        "Shutting down connection (%p)\n",
1013        connection);
1014   GNUNET_assert (NULL == connection->nth.notify_ready);
1015   GNUNET_assert (NULL == connection->receiver);
1016   if (NULL != connection->write_task)
1017   {
1018     GNUNET_SCHEDULER_cancel (connection->write_task);
1019     connection->write_task = NULL;
1020     connection->write_buffer_off = 0;
1021   }
1022   if (NULL != connection->read_task)
1023   {
1024     GNUNET_SCHEDULER_cancel (connection->read_task);
1025     connection->read_task = NULL;
1026   }
1027   if (NULL != connection->nth.timeout_task)
1028   {
1029     GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
1030     connection->nth.timeout_task = NULL;
1031   }
1032   connection->nth.notify_ready = NULL;
1033   if (NULL != connection->dns_active)
1034   {
1035     GNUNET_RESOLVER_request_cancel (connection->dns_active);
1036     connection->dns_active = NULL;
1037   }
1038   while (NULL != (pos = connection->ap_head))
1039   {
1040     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
1041     GNUNET_SCHEDULER_cancel (pos->task);
1042     GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, pos);
1043     GNUNET_free (pos);
1044   }
1045   if ( (NULL != connection->sock) &&
1046        (GNUNET_YES != connection->persist) )
1047   {
1048     if ((GNUNET_OK !=
1049          GNUNET_NETWORK_socket_shutdown (connection->sock,
1050                                          SHUT_RDWR)) &&
1051         (ENOTCONN != errno) &&
1052         (ECONNRESET != errno) )
1053       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
1054                     "shutdown");
1055   }
1056   if (NULL != connection->sock)
1057   {
1058     if (GNUNET_YES != connection->persist)
1059     {
1060       GNUNET_break (GNUNET_OK ==
1061                     GNUNET_NETWORK_socket_close (connection->sock));
1062     }
1063     else
1064     {
1065       GNUNET_NETWORK_socket_free_memory_only_ (connection->sock); /* at least no memory leak (we deliberately
1066                                                                    * leak the socket in this special case) ... */
1067     }
1068   }
1069   GNUNET_free_non_null (connection->addr);
1070   GNUNET_free_non_null (connection->hostname);
1071   GNUNET_free (connection->write_buffer);
1072   GNUNET_free (connection);
1073 }
1074
1075
1076 /**
1077  * This function is called once we either timeout
1078  * or have data ready to read.
1079  *
1080  * @param cls connection to read from
1081  * @param tc scheduler context
1082  */
1083 static void
1084 receive_ready (void *cls,
1085                const struct GNUNET_SCHEDULER_TaskContext *tc)
1086 {
1087   struct GNUNET_CONNECTION_Handle *connection = cls;
1088   char buffer[connection->max];
1089   ssize_t ret;
1090   GNUNET_CONNECTION_Receiver receiver;
1091
1092   connection->read_task = NULL;
1093   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1094   {
1095     /* ignore shutdown request, go again immediately */
1096     connection->read_task =
1097         GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1098                                        (connection->receive_timeout), connection->sock,
1099                                        &receive_ready, connection);
1100     return;
1101   }
1102   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1103   {
1104     LOG (GNUNET_ERROR_TYPE_DEBUG,
1105          "Receive from `%s' encounters error: timeout (%s, %p)\n",
1106          GNUNET_a2s (connection->addr, connection->addrlen),
1107          GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (connection->receive_timeout), GNUNET_YES),
1108          connection);
1109     signal_receive_timeout (connection);
1110     return;
1111   }
1112   if (NULL == connection->sock)
1113   {
1114     /* connect failed for good */
1115     signal_receive_error (connection, ECONNREFUSED);
1116     return;
1117   }
1118   GNUNET_assert (GNUNET_NETWORK_fdset_isset (tc->read_ready, connection->sock));
1119 RETRY:
1120   ret = GNUNET_NETWORK_socket_recv (connection->sock,
1121                                     buffer,
1122                                     connection->max);
1123   if (-1 == ret)
1124   {
1125     if (EINTR == errno)
1126       goto RETRY;
1127     signal_receive_error (connection, errno);
1128     return;
1129   }
1130   LOG (GNUNET_ERROR_TYPE_DEBUG,
1131        "receive_ready read %u/%u bytes from `%s' (%p)!\n",
1132        (unsigned int) ret,
1133        connection->max,
1134        GNUNET_a2s (connection->addr,
1135                    connection->addrlen),
1136        connection);
1137   GNUNET_assert (NULL != (receiver = connection->receiver));
1138   connection->receiver = NULL;
1139   receiver (connection->receiver_cls,
1140             buffer,
1141             ret,
1142             connection->addr,
1143             connection->addrlen,
1144             0);
1145 }
1146
1147
1148 /**
1149  * Receive data from the given connection.  Note that this function will
1150  * call @a receiver asynchronously using the scheduler.  It will
1151  * "immediately" return.  Note that there MUST only be one active
1152  * receive call per connection at any given point in time (so do not
1153  * call receive again until the receiver callback has been invoked).
1154  *
1155  * @param connection connection handle
1156  * @param max maximum number of bytes to read
1157  * @param timeout maximum amount of time to wait
1158  * @param receiver function to call with received data
1159  * @param receiver_cls closure for @a receiver
1160  */
1161 void
1162 GNUNET_CONNECTION_receive (struct GNUNET_CONNECTION_Handle *connection,
1163                            size_t max,
1164                            struct GNUNET_TIME_Relative timeout,
1165                            GNUNET_CONNECTION_Receiver receiver,
1166                            void *receiver_cls)
1167 {
1168   GNUNET_assert ((NULL == connection->read_task) &&
1169                  (NULL == connection->receiver));
1170   GNUNET_assert (NULL != receiver);
1171   connection->receiver = receiver;
1172   connection->receiver_cls = receiver_cls;
1173   connection->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1174   connection->max = max;
1175   if (NULL != connection->sock)
1176   {
1177     connection->read_task =
1178       GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1179                                      (connection->receive_timeout),
1180                                      connection->sock,
1181                                      &receive_ready,
1182                                      connection);
1183     return;
1184   }
1185   if ((NULL == connection->dns_active) && (NULL == connection->ap_head))
1186   {
1187     connection->receiver = NULL;
1188     receiver (receiver_cls, NULL, 0, NULL, 0, ETIMEDOUT);
1189     return;
1190   }
1191 }
1192
1193
1194 /**
1195  * Cancel receive job on the given connection.  Note that the
1196  * receiver callback must not have been called yet in order
1197  * for the cancellation to be valid.
1198  *
1199  * @param connection connection handle
1200  * @return closure of the original receiver callback closure
1201  */
1202 void *
1203 GNUNET_CONNECTION_receive_cancel (struct GNUNET_CONNECTION_Handle *connection)
1204 {
1205   if (NULL != connection->read_task)
1206   {
1207     GNUNET_assert (connection ==
1208                    GNUNET_SCHEDULER_cancel (connection->read_task));
1209     connection->read_task = NULL;
1210   }
1211   connection->receiver = NULL;
1212   return connection->receiver_cls;
1213 }
1214
1215
1216 /**
1217  * Try to call the transmit notify method (check if we do
1218  * have enough space available first)!
1219  *
1220  * @param connection connection for which we should do this processing
1221  * @return #GNUNET_YES if we were able to call notify
1222  */
1223 static int
1224 process_notify (struct GNUNET_CONNECTION_Handle *connection)
1225 {
1226   size_t used;
1227   size_t avail;
1228   size_t size;
1229   GNUNET_CONNECTION_TransmitReadyNotify notify;
1230
1231   LOG (GNUNET_ERROR_TYPE_DEBUG,
1232        "process_notify is running\n");
1233   GNUNET_assert (NULL == connection->write_task);
1234   if (NULL == (notify = connection->nth.notify_ready))
1235   {
1236     LOG (GNUNET_ERROR_TYPE_DEBUG,
1237          "No one to notify\n");
1238     return GNUNET_NO;
1239   }
1240   used = connection->write_buffer_off - connection->write_buffer_pos;
1241   avail = connection->write_buffer_size - used;
1242   size = connection->nth.notify_size;
1243   if (size > avail)
1244   {
1245     LOG (GNUNET_ERROR_TYPE_DEBUG,
1246          "Not enough buffer\n");
1247     return GNUNET_NO;
1248   }
1249   connection->nth.notify_ready = NULL;
1250   if (connection->write_buffer_size - connection->write_buffer_off < size)
1251   {
1252     /* need to compact */
1253     memmove (connection->write_buffer,
1254              &connection->write_buffer[connection->write_buffer_pos],
1255              used);
1256     connection->write_buffer_off -= connection->write_buffer_pos;
1257     connection->write_buffer_pos = 0;
1258   }
1259   avail = connection->write_buffer_size - connection->write_buffer_off;
1260   GNUNET_assert (avail >= size);
1261   size =
1262       notify (connection->nth.notify_ready_cls, avail,
1263               &connection->write_buffer[connection->write_buffer_off]);
1264   GNUNET_assert (size <= avail);
1265   if (0 != size)
1266     connection->write_buffer_off += size;
1267   return GNUNET_YES;
1268 }
1269
1270
1271 /**
1272  * Task invoked by the scheduler when a call to transmit
1273  * is timing out (we never got enough buffer space to call
1274  * the callback function before the specified timeout
1275  * expired).
1276  *
1277  * This task notifies the client about the timeout.
1278  *
1279  * @param cls the `struct GNUNET_CONNECTION_Handle`
1280  * @param tc scheduler context
1281  */
1282 static void
1283 transmit_timeout (void *cls,
1284                   const struct GNUNET_SCHEDULER_TaskContext *tc)
1285 {
1286   struct GNUNET_CONNECTION_Handle *connection = cls;
1287   GNUNET_CONNECTION_TransmitReadyNotify notify;
1288
1289   connection->nth.timeout_task = NULL;
1290   LOG (GNUNET_ERROR_TYPE_DEBUG,
1291        "Transmit to `%s:%u/%s' fails, time out reached (%p).\n",
1292        connection->hostname,
1293        connection->port,
1294        GNUNET_a2s (connection->addr,
1295                    connection->addrlen),
1296        connection);
1297   notify = connection->nth.notify_ready;
1298   GNUNET_assert (NULL != notify);
1299   connection->nth.notify_ready = NULL;
1300   notify (connection->nth.notify_ready_cls, 0, NULL);
1301 }
1302
1303
1304 /**
1305  * Task invoked by the scheduler when we failed to connect
1306  * at the time of being asked to transmit.
1307  *
1308  * This task notifies the client about the error.
1309  *
1310  * @param cls the `struct GNUNET_CONNECTION_Handle`
1311  * @param tc scheduler context
1312  */
1313 static void
1314 connect_error (void *cls,
1315                const struct GNUNET_SCHEDULER_TaskContext *tc)
1316 {
1317   struct GNUNET_CONNECTION_Handle *connection = cls;
1318   GNUNET_CONNECTION_TransmitReadyNotify notify;
1319
1320   LOG (GNUNET_ERROR_TYPE_DEBUG,
1321        "Transmission request of size %u fails (%s/%u), connection failed (%p).\n",
1322        connection->nth.notify_size,
1323        connection->hostname,
1324        connection->port,
1325        connection);
1326   connection->write_task = NULL;
1327   notify = connection->nth.notify_ready;
1328   connection->nth.notify_ready = NULL;
1329   notify (connection->nth.notify_ready_cls, 0, NULL);
1330 }
1331
1332
1333 /**
1334  * We are ready to transmit (or got a timeout).
1335  *
1336  * @param cls our connection handle
1337  * @param tc task context describing why we are here
1338  */
1339 static void
1340 transmit_ready (void *cls,
1341                 const struct GNUNET_SCHEDULER_TaskContext *tc)
1342 {
1343   struct GNUNET_CONNECTION_Handle *connection = cls;
1344   GNUNET_CONNECTION_TransmitReadyNotify notify;
1345   ssize_t ret;
1346   size_t have;
1347
1348   LOG (GNUNET_ERROR_TYPE_DEBUG,
1349        "transmit_ready running (%p).\n",
1350        connection);
1351   GNUNET_assert (NULL != connection->write_task);
1352   connection->write_task = NULL;
1353   GNUNET_assert (NULL == connection->nth.timeout_task);
1354   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1355   {
1356     if (NULL != connection->sock)
1357       goto SCHEDULE_WRITE;      /* ignore shutdown, go again immediately */
1358     LOG (GNUNET_ERROR_TYPE_DEBUG,
1359          "Transmit to `%s' fails, shutdown happened (%p).\n",
1360          GNUNET_a2s (connection->addr, connection->addrlen), connection);
1361     notify = connection->nth.notify_ready;
1362     if (NULL != notify)
1363     {
1364       connection->nth.notify_ready = NULL;
1365       notify (connection->nth.notify_ready_cls, 0, NULL);
1366     }
1367     return;
1368   }
1369   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1370   {
1371     LOG (GNUNET_ERROR_TYPE_DEBUG,
1372          "Transmit to `%s' fails, time out reached (%p).\n",
1373          GNUNET_a2s (connection->addr,
1374                      connection->addrlen),
1375          connection);
1376     notify = connection->nth.notify_ready;
1377     GNUNET_assert (NULL != notify);
1378     connection->nth.notify_ready = NULL;
1379     notify (connection->nth.notify_ready_cls, 0, NULL);
1380     return;
1381   }
1382   GNUNET_assert (NULL != connection->sock);
1383   if (NULL == tc->write_ready)
1384   {
1385     /* special circumstances (in particular, PREREQ_DONE after
1386      * connect): not yet ready to write, but no "fatal" error either.
1387      * Hence retry.  */
1388     goto SCHEDULE_WRITE;
1389   }
1390   if (!GNUNET_NETWORK_fdset_isset (tc->write_ready, connection->sock))
1391   {
1392     GNUNET_assert (NULL == connection->write_task);
1393     /* special circumstances (in particular, shutdown): not yet ready
1394      * to write, but no "fatal" error either.  Hence retry.  */
1395     goto SCHEDULE_WRITE;
1396   }
1397   GNUNET_assert (connection->write_buffer_off >= connection->write_buffer_pos);
1398   if ((NULL != connection->nth.notify_ready) &&
1399       (connection->write_buffer_size < connection->nth.notify_size))
1400   {
1401     connection->write_buffer =
1402         GNUNET_realloc (connection->write_buffer, connection->nth.notify_size);
1403     connection->write_buffer_size = connection->nth.notify_size;
1404   }
1405   process_notify (connection);
1406   have = connection->write_buffer_off - connection->write_buffer_pos;
1407   if (0 == have)
1408   {
1409     /* no data ready for writing, terminate write loop */
1410     return;
1411   }
1412   GNUNET_assert (have <= connection->write_buffer_size);
1413   GNUNET_assert (have + connection->write_buffer_pos <= connection->write_buffer_size);
1414   GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1415 RETRY:
1416   ret =
1417       GNUNET_NETWORK_socket_send (connection->sock,
1418                                   &connection->write_buffer[connection->write_buffer_pos],
1419                                   have);
1420   if (-1 == ret)
1421   {
1422     if (EINTR == errno)
1423       goto RETRY;
1424     if (NULL != connection->write_task)
1425     {
1426       GNUNET_SCHEDULER_cancel (connection->write_task);
1427       connection->write_task = NULL;
1428     }
1429     signal_transmit_error (connection, errno);
1430     return;
1431   }
1432   LOG (GNUNET_ERROR_TYPE_DEBUG,
1433        "Connection transmitted %u/%u bytes to `%s' (%p)\n",
1434        (unsigned int) ret, have, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1435   connection->write_buffer_pos += ret;
1436   if (connection->write_buffer_pos == connection->write_buffer_off)
1437   {
1438     /* transmitted all pending data */
1439     connection->write_buffer_pos = 0;
1440     connection->write_buffer_off = 0;
1441   }
1442   if ((0 == connection->write_buffer_off) && (NULL == connection->nth.notify_ready))
1443     return;                     /* all data sent! */
1444   /* not done writing, schedule more */
1445 SCHEDULE_WRITE:
1446   LOG (GNUNET_ERROR_TYPE_DEBUG,
1447        "Re-scheduling transmit_ready (more to do) (%p).\n", connection);
1448   have = connection->write_buffer_off - connection->write_buffer_pos;
1449   GNUNET_assert ((NULL != connection->nth.notify_ready) || (have > 0));
1450   if (NULL == connection->write_task)
1451     connection->write_task =
1452         GNUNET_SCHEDULER_add_write_net ((connection->nth.notify_ready ==
1453                                          NULL) ? GNUNET_TIME_UNIT_FOREVER_REL :
1454                                         GNUNET_TIME_absolute_get_remaining
1455                                         (connection->nth.transmit_timeout),
1456                                         connection->sock, &transmit_ready, connection);
1457 }
1458
1459
1460 /**
1461  * Ask the connection to call us once the specified number of bytes
1462  * are free in the transmission buffer.  Will never call the @a notify
1463  * callback in this task, but always first go into the scheduler.
1464  *
1465  * @param connection connection
1466  * @param size number of bytes to send
1467  * @param timeout after how long should we give up (and call
1468  *        @a notify with buf NULL and size 0)?
1469  * @param notify function to call
1470  * @param notify_cls closure for @a notify
1471  * @return non-NULL if the notify callback was queued,
1472  *         NULL if we are already going to notify someone else (busy)
1473  */
1474 struct GNUNET_CONNECTION_TransmitHandle *
1475 GNUNET_CONNECTION_notify_transmit_ready (struct GNUNET_CONNECTION_Handle *connection,
1476                                          size_t size,
1477                                          struct GNUNET_TIME_Relative timeout,
1478                                          GNUNET_CONNECTION_TransmitReadyNotify
1479                                          notify, void *notify_cls)
1480 {
1481   if (NULL != connection->nth.notify_ready)
1482   {
1483     GNUNET_assert (0);
1484     return NULL;
1485   }
1486   GNUNET_assert (NULL != notify);
1487   GNUNET_assert (size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1488   GNUNET_assert (connection->write_buffer_off <= connection->write_buffer_size);
1489   GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1490   GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_off);
1491   connection->nth.notify_ready = notify;
1492   connection->nth.notify_ready_cls = notify_cls;
1493   connection->nth.connection = connection;
1494   connection->nth.notify_size = size;
1495   connection->nth.transmit_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1496   GNUNET_assert (NULL == connection->nth.timeout_task);
1497   if ((NULL == connection->sock) &&
1498       (NULL == connection->ap_head) &&
1499       (NULL == connection->dns_active))
1500   {
1501     if (NULL != connection->write_task)
1502       GNUNET_SCHEDULER_cancel (connection->write_task);
1503     connection->write_task = GNUNET_SCHEDULER_add_now (&connect_error,
1504                                                        connection);
1505     return &connection->nth;
1506   }
1507   if (NULL != connection->write_task)
1508     return &connection->nth; /* previous transmission still in progress */
1509   if (NULL != connection->sock)
1510   {
1511     /* connected, try to transmit now */
1512     LOG (GNUNET_ERROR_TYPE_DEBUG,
1513          "Scheduling transmission (%p).\n",
1514          connection);
1515     connection->write_task =
1516         GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
1517                                         (connection->nth.transmit_timeout),
1518                                         connection->sock, &transmit_ready, connection);
1519     return &connection->nth;
1520   }
1521   /* not yet connected, wait for connection */
1522   LOG (GNUNET_ERROR_TYPE_DEBUG,
1523        "Need to wait to schedule transmission for connection, adding timeout task (%p).\n",
1524        connection);
1525   connection->nth.timeout_task =
1526     GNUNET_SCHEDULER_add_delayed (timeout,
1527                                   &transmit_timeout, connection);
1528   return &connection->nth;
1529 }
1530
1531
1532 /**
1533  * Cancel the specified transmission-ready notification.
1534  *
1535  * @param th notification to cancel
1536  */
1537 void
1538 GNUNET_CONNECTION_notify_transmit_ready_cancel (struct GNUNET_CONNECTION_TransmitHandle *th)
1539 {
1540   GNUNET_assert (NULL != th->notify_ready);
1541   th->notify_ready = NULL;
1542   if (NULL != th->timeout_task)
1543   {
1544     GNUNET_SCHEDULER_cancel (th->timeout_task);
1545     th->timeout_task = NULL;
1546   }
1547   if (NULL != th->connection->write_task)
1548   {
1549     GNUNET_SCHEDULER_cancel (th->connection->write_task);
1550     th->connection->write_task = NULL;
1551   }
1552 }
1553
1554 /* end of connection.c */