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