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