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