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