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