-check for EINPROGRESS for UNIX, hopefully fixing #2741
[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        (EINPROGRESS != errno) )
870   {
871     /* Just return; we expect everything to work eventually so don't fail HARD */
872     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (connection->sock));
873     connection->sock = NULL;
874     return connection;
875   }
876   connect_success_continuation (connection);
877   return connection;
878 #else
879   return NULL;
880 #endif
881 }
882
883
884 /**
885  * Create a connection handle by (asynchronously) connecting to a host.
886  * This function returns immediately, even if the connection has not
887  * yet been established.  This function only creates TCP connections.
888  *
889  * @param af_family address family to use
890  * @param serv_addr server address
891  * @param addrlen length of server address
892  * @return the connection handle
893  */
894 struct GNUNET_CONNECTION_Handle *
895 GNUNET_CONNECTION_create_from_sockaddr (int af_family,
896                                         const struct sockaddr *serv_addr,
897                                         socklen_t addrlen)
898 {
899   struct GNUNET_NETWORK_Handle *s;
900   struct GNUNET_CONNECTION_Handle *connection;
901
902   s = GNUNET_NETWORK_socket_create (af_family, SOCK_STREAM, 0);
903   if (NULL == s)
904   {
905     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, "socket");
906     return NULL;
907   }
908   if ((GNUNET_OK != GNUNET_NETWORK_socket_connect (s, serv_addr, addrlen)) &&
909       (EINPROGRESS != errno))
910   {
911     /* maybe refused / unsupported address, try next */
912     LOG_STRERROR (GNUNET_ERROR_TYPE_INFO, "connect");
913     LOG (GNUNET_ERROR_TYPE_INFO, _("Attempt to connect to `%s' failed\n"),
914          GNUNET_a2s (serv_addr, addrlen));
915     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (s));
916     return NULL;
917   }
918   connection = GNUNET_CONNECTION_create_from_existing (s);
919   connection->addr = GNUNET_malloc (addrlen);
920   memcpy (connection->addr, serv_addr, addrlen);
921   connection->addrlen = addrlen;
922   LOG (GNUNET_ERROR_TYPE_INFO, _("Trying to connect to `%s' (%p)\n"),
923        GNUNET_a2s (serv_addr, addrlen), connection);
924   return connection;
925 }
926
927
928 /**
929  * Check if connection is valid (no fatal errors have happened so far).
930  * Note that a connection that is still trying to connect is considered
931  * valid.
932  *
933  * @param connection connection to check
934  * @return GNUNET_YES if valid, GNUNET_NO otherwise
935  */
936 int
937 GNUNET_CONNECTION_check (struct GNUNET_CONNECTION_Handle *connection)
938 {
939   if ((NULL != connection->ap_head) || (NULL != connection->dns_active))
940     return GNUNET_YES;          /* still trying to connect */
941   return (NULL == connection->sock) ? GNUNET_NO : GNUNET_YES;
942 }
943
944
945 /**
946  * Close the connection and free associated resources.  There must
947  * not be any pending requests for reading or writing to the
948  * connection at this time.
949  *
950  * @param connection connection to destroy
951  */
952 void
953 GNUNET_CONNECTION_destroy (struct GNUNET_CONNECTION_Handle *connection)
954 {
955   struct AddressProbe *pos;
956
957   if (0 != connection->destroy_later)
958   {
959     connection->destroy_later = -1;
960     return;
961   }
962   LOG (GNUNET_ERROR_TYPE_DEBUG, "Shutting down connection (%p)\n", connection);
963   GNUNET_assert (NULL == connection->nth.notify_ready);
964   GNUNET_assert (NULL == connection->receiver);
965   if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
966   {
967     GNUNET_SCHEDULER_cancel (connection->write_task);
968     connection->write_task = GNUNET_SCHEDULER_NO_TASK;
969     connection->write_buffer_off = 0;
970   }
971   if (GNUNET_SCHEDULER_NO_TASK != connection->read_task)
972   {
973     GNUNET_SCHEDULER_cancel (connection->read_task);
974     connection->read_task = GNUNET_SCHEDULER_NO_TASK;
975   }
976   if (GNUNET_SCHEDULER_NO_TASK != connection->nth.timeout_task)
977   {
978     GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
979     connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
980   }
981   connection->nth.notify_ready = NULL;
982   if (NULL != connection->dns_active)
983   {
984     GNUNET_RESOLVER_request_cancel (connection->dns_active);
985     connection->dns_active = NULL;
986   }
987   while (NULL != (pos = connection->ap_head))
988   {
989     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
990     GNUNET_SCHEDULER_cancel (pos->task);
991     GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, pos);
992     GNUNET_free (pos);
993   }
994   if ( (NULL != connection->sock) &&
995        (GNUNET_YES != connection->persist) )
996   {
997     if ((GNUNET_YES != GNUNET_NETWORK_socket_shutdown (connection->sock, SHUT_RDWR)) && 
998         (ENOTCONN != errno) && 
999         (ECONNRESET != errno) )
1000       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "shutdown");    
1001   }
1002   if (NULL != connection->sock)
1003   {
1004     if (GNUNET_YES != connection->persist)
1005       GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (connection->sock));
1006     else
1007       GNUNET_free (connection->sock); /* at least no memory leak (we deliberately
1008                                        * leak the socket in this special case) ... */
1009   }
1010   GNUNET_free_non_null (connection->addr);
1011   GNUNET_free_non_null (connection->hostname);
1012   GNUNET_free (connection->write_buffer);
1013   GNUNET_free (connection);
1014 }
1015
1016
1017 /**
1018  * This function is called once we either timeout
1019  * or have data ready to read.
1020  *
1021  * @param cls connection to read from
1022  * @param tc scheduler context
1023  */
1024 static void
1025 receive_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1026 {
1027   struct GNUNET_CONNECTION_Handle *connection = cls;
1028   char buffer[connection->max];
1029   ssize_t ret;
1030   GNUNET_CONNECTION_Receiver receiver;
1031
1032   connection->read_task = GNUNET_SCHEDULER_NO_TASK;
1033   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1034   {
1035     /* ignore shutdown request, go again immediately */
1036     connection->read_task =
1037         GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1038                                        (connection->receive_timeout), connection->sock,
1039                                        &receive_ready, connection);
1040     return;
1041   }
1042   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1043   {
1044     LOG (GNUNET_ERROR_TYPE_DEBUG,
1045          "Receive from `%s' encounters error: timeout (%p)\n",
1046          GNUNET_a2s (connection->addr, connection->addrlen),
1047          GNUNET_TIME_absolute_get_duration (connection->receive_timeout).rel_value,
1048          connection);
1049     signal_receive_timeout (connection);
1050     return;
1051   }
1052   if (NULL == connection->sock)
1053   {
1054     /* connect failed for good */
1055     signal_receive_error (connection, ECONNREFUSED);
1056     return;
1057   }
1058   GNUNET_assert (GNUNET_NETWORK_fdset_isset (tc->read_ready, connection->sock));
1059 RETRY:
1060   ret = GNUNET_NETWORK_socket_recv (connection->sock, buffer, connection->max);
1061   if (-1 == ret)
1062   {
1063     if (EINTR == errno)
1064       goto RETRY;
1065     signal_receive_error (connection, errno);
1066     return;
1067   }
1068   LOG (GNUNET_ERROR_TYPE_DEBUG,
1069        "receive_ready read %u/%u bytes from `%s' (%p)!\n", (unsigned int) ret,
1070        connection->max, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1071   GNUNET_assert (NULL != (receiver = connection->receiver));
1072   connection->receiver = NULL;
1073   receiver (connection->receiver_cls, buffer, ret, connection->addr, connection->addrlen, 0);
1074 }
1075
1076
1077 /**
1078  * Receive data from the given connection.  Note that this function will
1079  * call "receiver" asynchronously using the scheduler.  It will
1080  * "immediately" return.  Note that there MUST only be one active
1081  * receive call per connection at any given point in time (so do not
1082  * call receive again until the receiver callback has been invoked).
1083  *
1084  * @param connection connection handle
1085  * @param max maximum number of bytes to read
1086  * @param timeout maximum amount of time to wait
1087  * @param receiver function to call with received data
1088  * @param receiver_cls closure for receiver
1089  */
1090 void
1091 GNUNET_CONNECTION_receive (struct GNUNET_CONNECTION_Handle *connection, size_t max,
1092                            struct GNUNET_TIME_Relative timeout,
1093                            GNUNET_CONNECTION_Receiver receiver,
1094                            void *receiver_cls)
1095 {
1096   GNUNET_assert ((GNUNET_SCHEDULER_NO_TASK == connection->read_task) &&
1097                  (NULL == connection->receiver));
1098   GNUNET_assert (NULL != receiver);
1099   connection->receiver = receiver;
1100   connection->receiver_cls = receiver_cls;
1101   connection->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1102   connection->max = max;
1103   if (NULL != connection->sock)
1104   {
1105     connection->read_task =
1106       GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1107                                      (connection->receive_timeout), connection->sock,
1108                                      &receive_ready, connection);
1109     return;
1110   }
1111   if ((NULL == connection->dns_active) && (NULL == connection->ap_head))
1112   {
1113     connection->receiver = NULL;
1114     receiver (receiver_cls, NULL, 0, NULL, 0, ETIMEDOUT);
1115     return;
1116   }
1117 }
1118
1119
1120 /**
1121  * Cancel receive job on the given connection.  Note that the
1122  * receiver callback must not have been called yet in order
1123  * for the cancellation to be valid.
1124  *
1125  * @param connection connection handle
1126  * @return closure of the original receiver callback closure
1127  */
1128 void *
1129 GNUNET_CONNECTION_receive_cancel (struct GNUNET_CONNECTION_Handle *connection)
1130 {
1131   if (GNUNET_SCHEDULER_NO_TASK != connection->read_task)
1132   {
1133     GNUNET_assert (connection == GNUNET_SCHEDULER_cancel (connection->read_task));
1134     connection->read_task = GNUNET_SCHEDULER_NO_TASK;
1135   }
1136   connection->receiver = NULL;
1137   return connection->receiver_cls;
1138 }
1139
1140
1141 /**
1142  * Try to call the transmit notify method (check if we do
1143  * have enough space available first)!
1144  *
1145  * @param connection connection for which we should do this processing
1146  * @return GNUNET_YES if we were able to call notify
1147  */
1148 static int
1149 process_notify (struct GNUNET_CONNECTION_Handle *connection)
1150 {
1151   size_t used;
1152   size_t avail;
1153   size_t size;
1154   GNUNET_CONNECTION_TransmitReadyNotify notify;
1155
1156   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
1157   if (NULL == (notify = connection->nth.notify_ready))
1158     return GNUNET_NO;
1159   used = connection->write_buffer_off - connection->write_buffer_pos;
1160   avail = connection->write_buffer_size - used;
1161   size = connection->nth.notify_size;
1162   if (size > avail)
1163     return GNUNET_NO;
1164   connection->nth.notify_ready = NULL;
1165   if (connection->write_buffer_size - connection->write_buffer_off < size)
1166   {
1167     /* need to compact */
1168     memmove (connection->write_buffer, &connection->write_buffer[connection->write_buffer_pos],
1169              used);
1170     connection->write_buffer_off -= connection->write_buffer_pos;
1171     connection->write_buffer_pos = 0;
1172   }
1173   avail = connection->write_buffer_size - connection->write_buffer_off;
1174   GNUNET_assert (avail >= size);
1175   size =
1176       notify (connection->nth.notify_ready_cls, avail,
1177               &connection->write_buffer[connection->write_buffer_off]);
1178   GNUNET_assert (size <= avail);
1179   if (0 != size)
1180     connection->write_buffer_off += size;
1181   return GNUNET_YES;
1182 }
1183
1184
1185 /**
1186  * Task invoked by the scheduler when a call to transmit
1187  * is timing out (we never got enough buffer space to call
1188  * the callback function before the specified timeout
1189  * expired).
1190  *
1191  * This task notifies the client about the timeout.
1192  *
1193  * @param cls the 'struct GNUNET_CONNECTION_Handle'
1194  * @param tc scheduler context
1195  */
1196 static void
1197 transmit_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1198 {
1199   struct GNUNET_CONNECTION_Handle *connection = cls;
1200   GNUNET_CONNECTION_TransmitReadyNotify notify;
1201
1202   connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
1203   LOG (GNUNET_ERROR_TYPE_DEBUG,
1204        "Transmit to `%s:%u/%s' fails, time out reached (%p).\n",
1205        connection->hostname,
1206        connection->port, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1207   notify = connection->nth.notify_ready;
1208   GNUNET_assert (NULL != notify);
1209   connection->nth.notify_ready = NULL;
1210   notify (connection->nth.notify_ready_cls, 0, NULL);
1211 }
1212
1213
1214 /**
1215  * Task invoked by the scheduler when we failed to connect
1216  * at the time of being asked to transmit.
1217  *
1218  * This task notifies the client about the error.
1219  *
1220  * @param cls the 'struct GNUNET_CONNECTION_Handle'
1221  * @param tc scheduler context
1222  */
1223 static void
1224 connect_error (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1225 {
1226   struct GNUNET_CONNECTION_Handle *connection = cls;
1227   GNUNET_CONNECTION_TransmitReadyNotify notify;
1228
1229   LOG (GNUNET_ERROR_TYPE_DEBUG,
1230        "Transmission request of size %u fails (%s/%u), connection failed (%p).\n",
1231        connection->nth.notify_size, connection->hostname, connection->port, connection);
1232   connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1233   notify = connection->nth.notify_ready;
1234   connection->nth.notify_ready = NULL;
1235   notify (connection->nth.notify_ready_cls, 0, NULL);
1236 }
1237
1238
1239 /**
1240  * We are ready to transmit (or got a timeout).
1241  *
1242  * @param cls our connection handle
1243  * @param tc task context describing why we are here
1244  */
1245 static void
1246 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1247 {
1248   struct GNUNET_CONNECTION_Handle *connection = cls;
1249   GNUNET_CONNECTION_TransmitReadyNotify notify;
1250   ssize_t ret;
1251   size_t have;
1252
1253   LOG (GNUNET_ERROR_TYPE_DEBUG, "transmit_ready running (%p).\n", connection);
1254   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != connection->write_task);
1255   connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1256   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->nth.timeout_task);
1257   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1258   {
1259     if (NULL != connection->sock)
1260       goto SCHEDULE_WRITE;      /* ignore shutdown, go again immediately */
1261     LOG (GNUNET_ERROR_TYPE_DEBUG,
1262          "Transmit to `%s' fails, shutdown happened (%p).\n",
1263          GNUNET_a2s (connection->addr, connection->addrlen), connection);
1264     notify = connection->nth.notify_ready;
1265     if (NULL != notify)
1266     {
1267       connection->nth.notify_ready = NULL;
1268       notify (connection->nth.notify_ready_cls, 0, NULL);
1269     }
1270     return;
1271   }
1272   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1273   {
1274     LOG (GNUNET_ERROR_TYPE_DEBUG,
1275          "Transmit to `%s' fails, time out reached (%p).\n",
1276          GNUNET_a2s (connection->addr, connection->addrlen), connection);
1277     notify = connection->nth.notify_ready;
1278     GNUNET_assert (NULL != notify);
1279     connection->nth.notify_ready = NULL;
1280     notify (connection->nth.notify_ready_cls, 0, NULL);
1281     return;
1282   }
1283   GNUNET_assert (NULL != connection->sock);
1284   if (NULL == tc->write_ready) 
1285   {
1286     /* special circumstances (in particular, PREREQ_DONE after
1287      * connect): not yet ready to write, but no "fatal" error either.
1288      * Hence retry.  */
1289     goto SCHEDULE_WRITE;
1290   }
1291   if (!GNUNET_NETWORK_fdset_isset (tc->write_ready, connection->sock))
1292   {
1293     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
1294     /* special circumstances (in particular, shutdown): not yet ready
1295      * to write, but no "fatal" error either.  Hence retry.  */
1296     goto SCHEDULE_WRITE;
1297   }
1298   GNUNET_assert (connection->write_buffer_off >= connection->write_buffer_pos);
1299   if ((NULL != connection->nth.notify_ready) &&
1300       (connection->write_buffer_size < connection->nth.notify_size))
1301   {
1302     connection->write_buffer =
1303         GNUNET_realloc (connection->write_buffer, connection->nth.notify_size);
1304     connection->write_buffer_size = connection->nth.notify_size;
1305   }
1306   process_notify (connection);
1307   have = connection->write_buffer_off - connection->write_buffer_pos;
1308   if (0 == have)
1309   {
1310     /* no data ready for writing, terminate write loop */
1311     return;
1312   }
1313   GNUNET_assert (have <= connection->write_buffer_size);
1314   GNUNET_assert (have + connection->write_buffer_pos <= connection->write_buffer_size);
1315   GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1316 RETRY:
1317   ret =
1318       GNUNET_NETWORK_socket_send (connection->sock,
1319                                   &connection->write_buffer[connection->write_buffer_pos],
1320                                   have);
1321   if (-1 == ret)
1322   {
1323     if (EINTR == errno)
1324       goto RETRY;
1325     if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
1326     {
1327       GNUNET_SCHEDULER_cancel (connection->write_task);
1328       connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1329     }
1330     signal_transmit_error (connection, errno);
1331     return;
1332   }
1333   LOG (GNUNET_ERROR_TYPE_DEBUG,
1334        "Connection transmitted %u/%u bytes to `%s' (%p)\n",
1335        (unsigned int) ret, have, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1336   connection->write_buffer_pos += ret;
1337   if (connection->write_buffer_pos == connection->write_buffer_off)
1338   {
1339     /* transmitted all pending data */
1340     connection->write_buffer_pos = 0;
1341     connection->write_buffer_off = 0;
1342   }
1343   if ((0 == connection->write_buffer_off) && (NULL == connection->nth.notify_ready))
1344     return;                     /* all data sent! */
1345   /* not done writing, schedule more */
1346 SCHEDULE_WRITE:
1347   LOG (GNUNET_ERROR_TYPE_DEBUG,
1348        "Re-scheduling transmit_ready (more to do) (%p).\n", connection);
1349   have = connection->write_buffer_off - connection->write_buffer_pos;
1350   GNUNET_assert ((NULL != connection->nth.notify_ready) || (have > 0));
1351   if (GNUNET_SCHEDULER_NO_TASK == connection->write_task)
1352     connection->write_task =
1353         GNUNET_SCHEDULER_add_write_net ((connection->nth.notify_ready ==
1354                                          NULL) ? GNUNET_TIME_UNIT_FOREVER_REL :
1355                                         GNUNET_TIME_absolute_get_remaining
1356                                         (connection->nth.transmit_timeout),
1357                                         connection->sock, &transmit_ready, connection);
1358 }
1359
1360
1361 /**
1362  * Ask the connection to call us once the specified number of bytes
1363  * are free in the transmission buffer.  May call the notify
1364  * method immediately if enough space is available.
1365  *
1366  * @param connection connection
1367  * @param size number of bytes to send
1368  * @param timeout after how long should we give up (and call
1369  *        notify with buf NULL and size 0)?
1370  * @param notify function to call
1371  * @param notify_cls closure for notify
1372  * @return non-NULL if the notify callback was queued,
1373  *         NULL if we are already going to notify someone else (busy)
1374  */
1375 struct GNUNET_CONNECTION_TransmitHandle *
1376 GNUNET_CONNECTION_notify_transmit_ready (struct GNUNET_CONNECTION_Handle *connection,
1377                                          size_t size,
1378                                          struct GNUNET_TIME_Relative timeout,
1379                                          GNUNET_CONNECTION_TransmitReadyNotify
1380                                          notify, void *notify_cls)
1381 {
1382   if (NULL != connection->nth.notify_ready)
1383   {
1384     GNUNET_assert (0);
1385     return NULL;
1386   }
1387   GNUNET_assert (NULL != notify);
1388   GNUNET_assert (size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1389   GNUNET_assert (connection->write_buffer_off <= connection->write_buffer_size);
1390   GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1391   GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_off);
1392   connection->nth.notify_ready = notify;
1393   connection->nth.notify_ready_cls = notify_cls;
1394   connection->nth.connection = connection;
1395   connection->nth.notify_size = size;
1396   connection->nth.transmit_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1397   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->nth.timeout_task);
1398   if ((NULL == connection->sock) && 
1399       (NULL == connection->ap_head) &&
1400       (NULL == connection->dns_active))
1401   {
1402     if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
1403       GNUNET_SCHEDULER_cancel (connection->write_task);
1404     connection->write_task = GNUNET_SCHEDULER_add_now (&connect_error, connection);
1405     return &connection->nth;
1406   }
1407   if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
1408     return &connection->nth; /* previous transmission still in progress */
1409   if (NULL != connection->sock)
1410   {
1411     /* connected, try to transmit now */
1412     LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduling transmission (%p).\n", connection);
1413     connection->write_task =
1414         GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
1415                                         (connection->nth.transmit_timeout),
1416                                         connection->sock, &transmit_ready, connection);
1417     return &connection->nth;
1418   }
1419   /* not yet connected, wait for connection */
1420   LOG (GNUNET_ERROR_TYPE_DEBUG,
1421        "Need to wait to schedule transmission for connection, adding timeout task (%p).\n", connection);
1422   connection->nth.timeout_task =
1423     GNUNET_SCHEDULER_add_delayed (timeout, &transmit_timeout, connection);
1424   return &connection->nth;
1425 }
1426
1427
1428 /**
1429  * Cancel the specified transmission-ready notification.
1430  *
1431  * @param th notification to cancel
1432  */
1433 void
1434 GNUNET_CONNECTION_notify_transmit_ready_cancel (struct
1435                                                 GNUNET_CONNECTION_TransmitHandle
1436                                                 *th)
1437 {
1438   GNUNET_assert (NULL != th->notify_ready);
1439   th->notify_ready = NULL;
1440   if (GNUNET_SCHEDULER_NO_TASK != th->timeout_task)
1441   {
1442     GNUNET_SCHEDULER_cancel (th->timeout_task);
1443     th->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1444   }
1445   if (GNUNET_SCHEDULER_NO_TASK != th->connection->write_task)
1446   {
1447     GNUNET_SCHEDULER_cancel (th->connection->write_task);
1448     th->connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1449   }
1450 }
1451
1452 /* end of connection.c */