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