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