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