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