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