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