-try force binding client socket to loopback/localhost for localhost connections...
[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   ap->sock = GNUNET_NETWORK_socket_create (ap->addr->sa_family, SOCK_STREAM, 0);
737   if (NULL == ap->sock)
738   {
739     GNUNET_free (ap);
740     return;                     /* not supported by OS */
741   }
742   switch (ap->addr->sa_family)
743   {
744   case AF_INET:
745     {
746       struct sockaddr_in bnd;
747
748       ((struct sockaddr_in *) ap->addr)->sin_port = htons (connection->port);
749
750       bnd.sin_family = AF_INET;
751       bnd.sin_port = htons (0);
752       bnd.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
753 #if HAVE_SOCKADDR_IN_SIN_LEN
754       bnd.sin_len = sizeof (bnd);
755 #endif
756       if (0 == memcmp (&bnd.sin_addr.s_addr,
757                        &((struct sockaddr_in *) ap->addr)->sin_addr.s_addr,
758                        sizeof (bnd.sin_addr.s_addr)))
759       {
760         /* bind source IP to FORCE it to be loopback */
761         (void) GNUNET_NETWORK_socket_bind (ap->sock, 
762                                            (const struct sockaddr *) &bnd,
763                                            sizeof (bnd));
764       }
765     }
766     break;
767   case AF_INET6:
768     {
769       struct sockaddr_in6 bnd;
770
771       ((struct sockaddr_in6 *) ap->addr)->sin6_port = htons (connection->port);
772     
773       bnd.sin6_family = AF_INET6;
774       bnd.sin6_port = htons (0);
775       bnd.sin6_addr = in6addr_loopback;
776 #if HAVE_SOCKADDR_IN_SIN_LEN
777       bnd.sin6_len = sizeof (bnd);
778 #endif
779       if (0 == memcmp (&bnd.sin6_addr,
780                        &((struct sockaddr_in6 *) ap->addr)->sin6_addr,
781                        sizeof (bnd.sin6_addr)))
782       {
783         /* bind source IP to FORCE it to be loopback */
784         (void) GNUNET_NETWORK_socket_bind (ap->sock, 
785                                            (const struct sockaddr *) &bnd, 
786                                            sizeof (bnd));
787       }
788     }
789     break;
790   default:
791     GNUNET_break (0);
792     GNUNET_free (ap);
793     return;                     /* not supported by us */
794   }
795   LOG (GNUNET_ERROR_TYPE_INFO, _("Trying to connect to `%s' (%p)\n"),
796        GNUNET_a2s (ap->addr, ap->addrlen), connection);
797   
798   if ((GNUNET_OK !=
799        GNUNET_NETWORK_socket_connect (ap->sock, ap->addr, ap->addrlen)) &&
800       (EINPROGRESS != errno))
801   {
802     /* maybe refused / unsupported address, try next */
803     LOG_STRERROR (GNUNET_ERROR_TYPE_INFO, "connect");
804     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (ap->sock));
805     GNUNET_free (ap);
806     return;
807   }
808   GNUNET_CONTAINER_DLL_insert (connection->ap_head, connection->ap_tail, ap);
809   delay = GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT;
810   if (NULL != connection->nth.notify_ready)
811     delay =
812         GNUNET_TIME_relative_min (delay,
813                                   GNUNET_TIME_absolute_get_remaining (connection->
814                                                                       nth.transmit_timeout));
815   if (NULL != connection->receiver)
816     delay =
817         GNUNET_TIME_relative_min (delay,
818                                   GNUNET_TIME_absolute_get_remaining
819                                   (connection->receive_timeout));
820   ap->task =
821       GNUNET_SCHEDULER_add_write_net (delay, ap->sock,
822                                       &connect_probe_continuation, ap);
823 }
824
825
826 /**
827  * Create a connection handle by (asynchronously) connecting to a host.
828  * This function returns immediately, even if the connection has not
829  * yet been established.  This function only creates TCP connections.
830  *
831  * @param cfg configuration to use
832  * @param hostname name of the host to connect to
833  * @param port port to connect to
834  * @return the connection handle
835  */
836 struct GNUNET_CONNECTION_Handle *
837 GNUNET_CONNECTION_create_from_connect (const struct GNUNET_CONFIGURATION_Handle
838                                        *cfg, const char *hostname,
839                                        uint16_t port)
840 {
841   struct GNUNET_CONNECTION_Handle *connection;
842
843   GNUNET_assert (0 < strlen (hostname));        /* sanity check */
844   connection = GNUNET_malloc (sizeof (struct GNUNET_CONNECTION_Handle));
845   connection->cfg = cfg;
846   connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
847   connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
848   connection->port = port;
849   connection->hostname = GNUNET_strdup (hostname);
850   connection->dns_active =
851       GNUNET_RESOLVER_ip_get (connection->hostname, AF_UNSPEC,
852                               GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT,
853                               &try_connect_using_address, connection);
854   return connection;
855 }
856
857
858 /**
859  * Create a connection handle by connecting to a UNIX domain service.
860  * This function returns immediately, even if the connection has not
861  * yet been established.  This function only creates UNIX connections.
862  *
863  * @param cfg configuration to use
864  * @param unixpath path to connect to
865  * @return the connection handle, NULL on systems without UNIX support
866  */
867 struct GNUNET_CONNECTION_Handle *
868 GNUNET_CONNECTION_create_from_connect_to_unixpath (const struct
869                                                    GNUNET_CONFIGURATION_Handle
870                                                    *cfg, const char *unixpath)
871 {
872 #ifdef AF_UNIX
873   struct GNUNET_CONNECTION_Handle *connection;
874   struct sockaddr_un *un;
875   size_t slen;
876
877   GNUNET_assert (0 < strlen (unixpath));        /* sanity check */
878   un = GNUNET_malloc (sizeof (struct sockaddr_un));
879   un->sun_family = AF_UNIX;
880   slen = strlen (unixpath);
881   if (slen >= sizeof (un->sun_path))
882     slen = sizeof (un->sun_path) - 1;
883   memcpy (un->sun_path, unixpath, slen);
884   un->sun_path[slen] = '\0';
885   slen = sizeof (struct sockaddr_un);
886 #if HAVE_SOCKADDR_IN_SIN_LEN
887   un->sun_len = (u_char) slen;
888 #endif
889 #if LINUX
890   un->sun_path[0] = '\0';
891 #endif
892   connection = GNUNET_malloc (sizeof (struct GNUNET_CONNECTION_Handle));
893   connection->cfg = cfg;
894   connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
895   connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
896   connection->port = 0;
897   connection->hostname = NULL;
898   connection->addr = (struct sockaddr *) un;
899   connection->addrlen = slen;
900   connection->sock = GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_STREAM, 0);
901   if (NULL == connection->sock)
902   {
903     GNUNET_free (connection->addr);
904     GNUNET_free (connection->write_buffer);
905     GNUNET_free (connection);
906     return NULL;
907   }
908   if (GNUNET_OK !=
909       GNUNET_NETWORK_socket_connect (connection->sock, connection->addr, connection->addrlen))
910   {
911     /* Just return; we expect everything to work eventually so don't fail HARD */
912     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (connection->sock));
913     connection->sock = NULL;
914     return connection;
915   }
916   connect_success_continuation (connection);
917   return connection;
918 #else
919   return NULL;
920 #endif
921 }
922
923
924 /**
925  * Create a connection handle by (asynchronously) connecting to a host.
926  * This function returns immediately, even if the connection has not
927  * yet been established.  This function only creates TCP connections.
928  *
929  * @param af_family address family to use
930  * @param serv_addr server address
931  * @param addrlen length of server address
932  * @return the connection handle
933  */
934 struct GNUNET_CONNECTION_Handle *
935 GNUNET_CONNECTION_create_from_sockaddr (int af_family,
936                                         const struct sockaddr *serv_addr,
937                                         socklen_t addrlen)
938 {
939   struct GNUNET_NETWORK_Handle *s;
940   struct GNUNET_CONNECTION_Handle *connection;
941
942   s = GNUNET_NETWORK_socket_create (af_family, SOCK_STREAM, 0);
943   if (NULL == s)
944   {
945     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, "socket");
946     return NULL;
947   }
948   if ((GNUNET_OK != GNUNET_NETWORK_socket_connect (s, serv_addr, addrlen)) &&
949       (EINPROGRESS != errno))
950   {
951     /* maybe refused / unsupported address, try next */
952     LOG_STRERROR (GNUNET_ERROR_TYPE_INFO, "connect");
953     LOG (GNUNET_ERROR_TYPE_INFO, _("Attempt to connect to `%s' failed\n"),
954          GNUNET_a2s (serv_addr, addrlen));
955     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (s));
956     return NULL;
957   }
958   connection = GNUNET_CONNECTION_create_from_existing (s);
959   connection->addr = GNUNET_malloc (addrlen);
960   memcpy (connection->addr, serv_addr, addrlen);
961   connection->addrlen = addrlen;
962   LOG (GNUNET_ERROR_TYPE_INFO, _("Trying to connect to `%s' (%p)\n"),
963        GNUNET_a2s (serv_addr, addrlen), connection);
964   return connection;
965 }
966
967
968 /**
969  * Check if connection is valid (no fatal errors have happened so far).
970  * Note that a connection that is still trying to connect is considered
971  * valid.
972  *
973  * @param connection connection to check
974  * @return GNUNET_YES if valid, GNUNET_NO otherwise
975  */
976 int
977 GNUNET_CONNECTION_check (struct GNUNET_CONNECTION_Handle *connection)
978 {
979   if ((NULL != connection->ap_head) || (NULL != connection->dns_active))
980     return GNUNET_YES;          /* still trying to connect */
981   return (NULL == connection->sock) ? GNUNET_NO : GNUNET_YES;
982 }
983
984
985 /**
986  * Close the connection and free associated resources.  There must
987  * not be any pending requests for reading or writing to the
988  * connection at this time.
989  *
990  * @param connection connection to destroy
991  */
992 void
993 GNUNET_CONNECTION_destroy (struct GNUNET_CONNECTION_Handle *connection)
994 {
995   struct AddressProbe *pos;
996
997   if (0 != connection->destroy_later)
998   {
999     connection->destroy_later = -1;
1000     return;
1001   }
1002   LOG (GNUNET_ERROR_TYPE_DEBUG, "Shutting down connection (%p)\n", connection);
1003   GNUNET_assert (NULL == connection->nth.notify_ready);
1004   GNUNET_assert (NULL == connection->receiver);
1005   if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
1006   {
1007     GNUNET_SCHEDULER_cancel (connection->write_task);
1008     connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1009     connection->write_buffer_off = 0;
1010   }
1011   if (GNUNET_SCHEDULER_NO_TASK != connection->read_task)
1012   {
1013     GNUNET_SCHEDULER_cancel (connection->read_task);
1014     connection->read_task = GNUNET_SCHEDULER_NO_TASK;
1015   }
1016   if (GNUNET_SCHEDULER_NO_TASK != connection->nth.timeout_task)
1017   {
1018     GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
1019     connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
1020   }
1021   connection->nth.notify_ready = NULL;
1022   if (NULL != connection->dns_active)
1023   {
1024     GNUNET_RESOLVER_request_cancel (connection->dns_active);
1025     connection->dns_active = NULL;
1026   }
1027   while (NULL != (pos = connection->ap_head))
1028   {
1029     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
1030     GNUNET_SCHEDULER_cancel (pos->task);
1031     GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, pos);
1032     GNUNET_free (pos);
1033   }
1034   if ( (NULL != connection->sock) &&
1035        (GNUNET_YES != connection->persist) )
1036   {
1037     if ((GNUNET_YES != GNUNET_NETWORK_socket_shutdown (connection->sock, SHUT_RDWR)) && 
1038         (ENOTCONN != errno) && 
1039         (ECONNRESET != errno) )
1040       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "shutdown");    
1041   }
1042   if (NULL != connection->sock)
1043   {
1044     if (GNUNET_YES != connection->persist)
1045       GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (connection->sock));
1046     else
1047       GNUNET_free (connection->sock); /* at least no memory leak (we deliberately
1048                                        * leak the socket in this special case) ... */
1049   }
1050   GNUNET_free_non_null (connection->addr);
1051   GNUNET_free_non_null (connection->hostname);
1052   GNUNET_free (connection->write_buffer);
1053   GNUNET_free (connection);
1054 }
1055
1056
1057 /**
1058  * This function is called once we either timeout
1059  * or have data ready to read.
1060  *
1061  * @param cls connection to read from
1062  * @param tc scheduler context
1063  */
1064 static void
1065 receive_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1066 {
1067   struct GNUNET_CONNECTION_Handle *connection = cls;
1068   char buffer[connection->max];
1069   ssize_t ret;
1070   GNUNET_CONNECTION_Receiver receiver;
1071
1072   connection->read_task = GNUNET_SCHEDULER_NO_TASK;
1073   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1074   {
1075     /* ignore shutdown request, go again immediately */
1076     connection->read_task =
1077         GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1078                                        (connection->receive_timeout), connection->sock,
1079                                        &receive_ready, connection);
1080     return;
1081   }
1082   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1083   {
1084     LOG (GNUNET_ERROR_TYPE_DEBUG,
1085          "Receive from `%s' encounters error: timeout (%p)\n",
1086          GNUNET_a2s (connection->addr, connection->addrlen),
1087          GNUNET_TIME_absolute_get_duration (connection->receive_timeout).rel_value,
1088          connection);
1089     signal_receive_timeout (connection);
1090     return;
1091   }
1092   if (NULL == connection->sock)
1093   {
1094     /* connect failed for good */
1095     signal_receive_error (connection, ECONNREFUSED);
1096     return;
1097   }
1098   GNUNET_assert (GNUNET_NETWORK_fdset_isset (tc->read_ready, connection->sock));
1099 RETRY:
1100   ret = GNUNET_NETWORK_socket_recv (connection->sock, buffer, connection->max);
1101   if (-1 == ret)
1102   {
1103     if (EINTR == errno)
1104       goto RETRY;
1105     signal_receive_error (connection, errno);
1106     return;
1107   }
1108   LOG (GNUNET_ERROR_TYPE_DEBUG,
1109        "receive_ready read %u/%u bytes from `%s' (%p)!\n", (unsigned int) ret,
1110        connection->max, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1111   GNUNET_assert (NULL != (receiver = connection->receiver));
1112   connection->receiver = NULL;
1113   receiver (connection->receiver_cls, buffer, ret, connection->addr, connection->addrlen, 0);
1114 }
1115
1116
1117 /**
1118  * Receive data from the given connection.  Note that this function will
1119  * call "receiver" asynchronously using the scheduler.  It will
1120  * "immediately" return.  Note that there MUST only be one active
1121  * receive call per connection at any given point in time (so do not
1122  * call receive again until the receiver callback has been invoked).
1123  *
1124  * @param connection connection handle
1125  * @param max maximum number of bytes to read
1126  * @param timeout maximum amount of time to wait
1127  * @param receiver function to call with received data
1128  * @param receiver_cls closure for receiver
1129  */
1130 void
1131 GNUNET_CONNECTION_receive (struct GNUNET_CONNECTION_Handle *connection, size_t max,
1132                            struct GNUNET_TIME_Relative timeout,
1133                            GNUNET_CONNECTION_Receiver receiver,
1134                            void *receiver_cls)
1135 {
1136   GNUNET_assert ((GNUNET_SCHEDULER_NO_TASK == connection->read_task) &&
1137                  (NULL == connection->receiver));
1138   GNUNET_assert (NULL != receiver);
1139   connection->receiver = receiver;
1140   connection->receiver_cls = receiver_cls;
1141   connection->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1142   connection->max = max;
1143   if (NULL != connection->sock)
1144   {
1145     connection->read_task =
1146       GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1147                                      (connection->receive_timeout), connection->sock,
1148                                      &receive_ready, connection);
1149     return;
1150   }
1151   if ((NULL == connection->dns_active) && (NULL == connection->ap_head))
1152   {
1153     connection->receiver = NULL;
1154     receiver (receiver_cls, NULL, 0, NULL, 0, ETIMEDOUT);
1155     return;
1156   }
1157 }
1158
1159
1160 /**
1161  * Cancel receive job on the given connection.  Note that the
1162  * receiver callback must not have been called yet in order
1163  * for the cancellation to be valid.
1164  *
1165  * @param connection connection handle
1166  * @return closure of the original receiver callback closure
1167  */
1168 void *
1169 GNUNET_CONNECTION_receive_cancel (struct GNUNET_CONNECTION_Handle *connection)
1170 {
1171   if (GNUNET_SCHEDULER_NO_TASK != connection->read_task)
1172   {
1173     GNUNET_assert (connection == GNUNET_SCHEDULER_cancel (connection->read_task));
1174     connection->read_task = GNUNET_SCHEDULER_NO_TASK;
1175   }
1176   connection->receiver = NULL;
1177   return connection->receiver_cls;
1178 }
1179
1180
1181 /**
1182  * Try to call the transmit notify method (check if we do
1183  * have enough space available first)!
1184  *
1185  * @param connection connection for which we should do this processing
1186  * @return GNUNET_YES if we were able to call notify
1187  */
1188 static int
1189 process_notify (struct GNUNET_CONNECTION_Handle *connection)
1190 {
1191   size_t used;
1192   size_t avail;
1193   size_t size;
1194   GNUNET_CONNECTION_TransmitReadyNotify notify;
1195
1196   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
1197   if (NULL == (notify = connection->nth.notify_ready))
1198     return GNUNET_NO;
1199   used = connection->write_buffer_off - connection->write_buffer_pos;
1200   avail = connection->write_buffer_size - used;
1201   size = connection->nth.notify_size;
1202   if (size > avail)
1203     return GNUNET_NO;
1204   connection->nth.notify_ready = NULL;
1205   if (connection->write_buffer_size - connection->write_buffer_off < size)
1206   {
1207     /* need to compact */
1208     memmove (connection->write_buffer, &connection->write_buffer[connection->write_buffer_pos],
1209              used);
1210     connection->write_buffer_off -= connection->write_buffer_pos;
1211     connection->write_buffer_pos = 0;
1212   }
1213   avail = connection->write_buffer_size - connection->write_buffer_off;
1214   GNUNET_assert (avail >= size);
1215   size =
1216       notify (connection->nth.notify_ready_cls, avail,
1217               &connection->write_buffer[connection->write_buffer_off]);
1218   GNUNET_assert (size <= avail);
1219   if (0 != size)
1220     connection->write_buffer_off += size;
1221   return GNUNET_YES;
1222 }
1223
1224
1225 /**
1226  * Task invoked by the scheduler when a call to transmit
1227  * is timing out (we never got enough buffer space to call
1228  * the callback function before the specified timeout
1229  * expired).
1230  *
1231  * This task notifies the client about the timeout.
1232  *
1233  * @param cls the 'struct GNUNET_CONNECTION_Handle'
1234  * @param tc scheduler context
1235  */
1236 static void
1237 transmit_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1238 {
1239   struct GNUNET_CONNECTION_Handle *connection = cls;
1240   GNUNET_CONNECTION_TransmitReadyNotify notify;
1241
1242   connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
1243   LOG (GNUNET_ERROR_TYPE_DEBUG,
1244        "Transmit to `%s:%u/%s' fails, time out reached (%p).\n",
1245        connection->hostname,
1246        connection->port, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1247   notify = connection->nth.notify_ready;
1248   GNUNET_assert (NULL != notify);
1249   connection->nth.notify_ready = NULL;
1250   notify (connection->nth.notify_ready_cls, 0, NULL);
1251 }
1252
1253
1254 /**
1255  * Task invoked by the scheduler when we failed to connect
1256  * at the time of being asked to transmit.
1257  *
1258  * This task notifies the client about the error.
1259  *
1260  * @param cls the 'struct GNUNET_CONNECTION_Handle'
1261  * @param tc scheduler context
1262  */
1263 static void
1264 connect_error (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1265 {
1266   struct GNUNET_CONNECTION_Handle *connection = cls;
1267   GNUNET_CONNECTION_TransmitReadyNotify notify;
1268
1269   LOG (GNUNET_ERROR_TYPE_DEBUG,
1270        "Transmission request of size %u fails (%s/%u), connection failed (%p).\n",
1271        connection->nth.notify_size, connection->hostname, connection->port, connection);
1272   connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1273   notify = connection->nth.notify_ready;
1274   connection->nth.notify_ready = NULL;
1275   notify (connection->nth.notify_ready_cls, 0, NULL);
1276 }
1277
1278
1279 /**
1280  * We are ready to transmit (or got a timeout).
1281  *
1282  * @param cls our connection handle
1283  * @param tc task context describing why we are here
1284  */
1285 static void
1286 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1287 {
1288   struct GNUNET_CONNECTION_Handle *connection = cls;
1289   GNUNET_CONNECTION_TransmitReadyNotify notify;
1290   ssize_t ret;
1291   size_t have;
1292
1293   LOG (GNUNET_ERROR_TYPE_DEBUG, "transmit_ready running (%p).\n", connection);
1294   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != connection->write_task);
1295   connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1296   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->nth.timeout_task);
1297   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1298   {
1299     if (NULL != connection->sock)
1300       goto SCHEDULE_WRITE;      /* ignore shutdown, go again immediately */
1301     LOG (GNUNET_ERROR_TYPE_DEBUG,
1302          "Transmit to `%s' fails, shutdown happened (%p).\n",
1303          GNUNET_a2s (connection->addr, connection->addrlen), connection);
1304     notify = connection->nth.notify_ready;
1305     if (NULL != notify)
1306     {
1307       connection->nth.notify_ready = NULL;
1308       notify (connection->nth.notify_ready_cls, 0, NULL);
1309     }
1310     return;
1311   }
1312   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1313   {
1314     LOG (GNUNET_ERROR_TYPE_DEBUG,
1315          "Transmit to `%s' fails, time out reached (%p).\n",
1316          GNUNET_a2s (connection->addr, connection->addrlen), connection);
1317     notify = connection->nth.notify_ready;
1318     GNUNET_assert (NULL != notify);
1319     connection->nth.notify_ready = NULL;
1320     notify (connection->nth.notify_ready_cls, 0, NULL);
1321     return;
1322   }
1323   GNUNET_assert (NULL != connection->sock);
1324   if (NULL == tc->write_ready) 
1325   {
1326     /* special circumstances (in particular, PREREQ_DONE after
1327      * connect): not yet ready to write, but no "fatal" error either.
1328      * Hence retry.  */
1329     goto SCHEDULE_WRITE;
1330   }
1331   if (!GNUNET_NETWORK_fdset_isset (tc->write_ready, connection->sock))
1332   {
1333     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
1334     /* special circumstances (in particular, shutdown): not yet ready
1335      * to write, but no "fatal" error either.  Hence retry.  */
1336     goto SCHEDULE_WRITE;
1337   }
1338   GNUNET_assert (connection->write_buffer_off >= connection->write_buffer_pos);
1339   if ((NULL != connection->nth.notify_ready) &&
1340       (connection->write_buffer_size < connection->nth.notify_size))
1341   {
1342     connection->write_buffer =
1343         GNUNET_realloc (connection->write_buffer, connection->nth.notify_size);
1344     connection->write_buffer_size = connection->nth.notify_size;
1345   }
1346   process_notify (connection);
1347   have = connection->write_buffer_off - connection->write_buffer_pos;
1348   if (0 == have)
1349   {
1350     /* no data ready for writing, terminate write loop */
1351     return;
1352   }
1353   GNUNET_assert (have <= connection->write_buffer_size);
1354   GNUNET_assert (have + connection->write_buffer_pos <= connection->write_buffer_size);
1355   GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1356 RETRY:
1357   ret =
1358       GNUNET_NETWORK_socket_send (connection->sock,
1359                                   &connection->write_buffer[connection->write_buffer_pos],
1360                                   have);
1361   if (-1 == ret)
1362   {
1363     if (EINTR == errno)
1364       goto RETRY;
1365     if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
1366     {
1367       GNUNET_SCHEDULER_cancel (connection->write_task);
1368       connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1369     }
1370     signal_transmit_error (connection, errno);
1371     return;
1372   }
1373   LOG (GNUNET_ERROR_TYPE_DEBUG,
1374        "Connection transmitted %u/%u bytes to `%s' (%p)\n",
1375        (unsigned int) ret, have, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1376   connection->write_buffer_pos += ret;
1377   if (connection->write_buffer_pos == connection->write_buffer_off)
1378   {
1379     /* transmitted all pending data */
1380     connection->write_buffer_pos = 0;
1381     connection->write_buffer_off = 0;
1382   }
1383   if ((0 == connection->write_buffer_off) && (NULL == connection->nth.notify_ready))
1384     return;                     /* all data sent! */
1385   /* not done writing, schedule more */
1386 SCHEDULE_WRITE:
1387   LOG (GNUNET_ERROR_TYPE_DEBUG,
1388        "Re-scheduling transmit_ready (more to do) (%p).\n", connection);
1389   have = connection->write_buffer_off - connection->write_buffer_pos;
1390   GNUNET_assert ((NULL != connection->nth.notify_ready) || (have > 0));
1391   if (GNUNET_SCHEDULER_NO_TASK == connection->write_task)
1392     connection->write_task =
1393         GNUNET_SCHEDULER_add_write_net ((connection->nth.notify_ready ==
1394                                          NULL) ? GNUNET_TIME_UNIT_FOREVER_REL :
1395                                         GNUNET_TIME_absolute_get_remaining
1396                                         (connection->nth.transmit_timeout),
1397                                         connection->sock, &transmit_ready, connection);
1398 }
1399
1400
1401 /**
1402  * Ask the connection to call us once the specified number of bytes
1403  * are free in the transmission buffer.  May call the notify
1404  * method immediately if enough space is available.
1405  *
1406  * @param connection connection
1407  * @param size number of bytes to send
1408  * @param timeout after how long should we give up (and call
1409  *        notify with buf NULL and size 0)?
1410  * @param notify function to call
1411  * @param notify_cls closure for notify
1412  * @return non-NULL if the notify callback was queued,
1413  *         NULL if we are already going to notify someone else (busy)
1414  */
1415 struct GNUNET_CONNECTION_TransmitHandle *
1416 GNUNET_CONNECTION_notify_transmit_ready (struct GNUNET_CONNECTION_Handle *connection,
1417                                          size_t size,
1418                                          struct GNUNET_TIME_Relative timeout,
1419                                          GNUNET_CONNECTION_TransmitReadyNotify
1420                                          notify, void *notify_cls)
1421 {
1422   if (NULL != connection->nth.notify_ready)
1423   {
1424     GNUNET_assert (0);
1425     return NULL;
1426   }
1427   GNUNET_assert (NULL != notify);
1428   GNUNET_assert (size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1429   GNUNET_assert (connection->write_buffer_off <= connection->write_buffer_size);
1430   GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1431   GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_off);
1432   connection->nth.notify_ready = notify;
1433   connection->nth.notify_ready_cls = notify_cls;
1434   connection->nth.connection = connection;
1435   connection->nth.notify_size = size;
1436   connection->nth.transmit_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1437   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->nth.timeout_task);
1438   if ((NULL == connection->sock) && 
1439       (NULL == connection->ap_head) &&
1440       (NULL == connection->dns_active))
1441   {
1442     if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
1443       GNUNET_SCHEDULER_cancel (connection->write_task);
1444     connection->write_task = GNUNET_SCHEDULER_add_now (&connect_error, connection);
1445     return &connection->nth;
1446   }
1447   if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
1448     return &connection->nth; /* previous transmission still in progress */
1449   if (NULL != connection->sock)
1450   {
1451     /* connected, try to transmit now */
1452     LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduling transmission (%p).\n", connection);
1453     connection->write_task =
1454         GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
1455                                         (connection->nth.transmit_timeout),
1456                                         connection->sock, &transmit_ready, connection);
1457     return &connection->nth;
1458   }
1459   /* not yet connected, wait for connection */
1460   LOG (GNUNET_ERROR_TYPE_DEBUG,
1461        "Need to wait to schedule transmission for connection, adding timeout task (%p).\n", connection);
1462   connection->nth.timeout_task =
1463     GNUNET_SCHEDULER_add_delayed (timeout, &transmit_timeout, connection);
1464   return &connection->nth;
1465 }
1466
1467
1468 /**
1469  * Cancel the specified transmission-ready notification.
1470  *
1471  * @param th notification to cancel
1472  */
1473 void
1474 GNUNET_CONNECTION_notify_transmit_ready_cancel (struct
1475                                                 GNUNET_CONNECTION_TransmitHandle
1476                                                 *th)
1477 {
1478   GNUNET_assert (NULL != th->notify_ready);
1479   th->notify_ready = NULL;
1480   if (GNUNET_SCHEDULER_NO_TASK != th->timeout_task)
1481   {
1482     GNUNET_SCHEDULER_cancel (th->timeout_task);
1483     th->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1484   }
1485   if (GNUNET_SCHEDULER_NO_TASK != th->connection->write_task)
1486   {
1487     GNUNET_SCHEDULER_cancel (th->connection->write_task);
1488     th->connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1489   }
1490 }
1491
1492 /* end of connection.c */