indentation
[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
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),
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"), GNUNET_a2s (uaddr, addrlen));
460     GNUNET_break (GNUNET_OK ==
461                   GNUNET_NETWORK_socket_shutdown (sock, SHUT_RDWR));
462     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
463     GNUNET_free (uaddr);
464     return NULL;
465   }
466   ret = GNUNET_malloc (sizeof (struct GNUNET_CONNECTION_Handle));
467   ret->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
468   ret->write_buffer = GNUNET_malloc (ret->write_buffer_size);
469   ret->addr = uaddr;
470   ret->addrlen = addrlen;
471   ret->sock = sock;
472 #if DEBUG_CONNECTION
473   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
474               _("Accepting connection from `%s': %p\n"),
475               GNUNET_a2s (uaddr, addrlen), ret);
476 #endif
477   return ret;
478 }
479
480 /**
481  * Obtain the network address of the other party.
482  *
483  * @param sock the client to get the address for
484  * @param addr where to store the address
485  * @param addrlen where to store the length of the address
486  * @return GNUNET_OK on success
487  */
488 int
489 GNUNET_CONNECTION_get_address (struct GNUNET_CONNECTION_Handle *sock,
490                                void **addr, size_t * addrlen)
491 {
492   if ((sock->addr == NULL) || (sock->addrlen == 0))
493     return GNUNET_NO;
494   *addr = GNUNET_malloc (sock->addrlen);
495   memcpy (*addr, sock->addr, sock->addrlen);
496   *addrlen = sock->addrlen;
497   return GNUNET_OK;
498 }
499
500
501 /**
502  * This function is called after establishing a connection either has
503  * succeeded or timed out.  Note that it is possible that the attempt
504  * timed out and that we're immediately retrying.  If we are retrying,
505  * we need to wait again (or timeout); if we succeeded, we need to
506  * wait for data (or timeout).
507  *
508  * @param cls our connection handle
509  * @param tc task context describing why we are here
510  */
511 static void
512 receive_again (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
513
514
515 /**
516  * Scheduler let us know that the connect task is finished (or was
517  * cancelled due to shutdown).  Now really clean up.
518  *
519  * @param cls our "struct GNUNET_CONNECTION_Handle *"
520  * @param tc unused
521  */
522 static void
523 destroy_continuation (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
524 {
525   struct GNUNET_CONNECTION_Handle *sock = cls;
526   GNUNET_CONNECTION_TransmitReadyNotify notify;
527   struct AddressProbe *pos;
528
529   sock->destroy_task = GNUNET_SCHEDULER_NO_TASK;
530   GNUNET_assert (sock->dns_active == NULL);
531   if (0 != (sock->ccs & COCO_TRANSMIT_READY))
532   {
533 #if DEBUG_CONNECTION
534     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
535                 "Destroy waits for CCS-TR to be done (%p)\n", sock);
536 #endif
537     sock->ccs |= COCO_DESTROY_CONTINUATION;
538     return;
539   }
540   if (sock->write_task != GNUNET_SCHEDULER_NO_TASK)
541   {
542 #if DEBUG_CONNECTION
543     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
544                 "Destroy waits for write_task to be done (%p)\n", sock);
545 #endif
546     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == sock->destroy_task);
547     sock->destroy_task
548         = GNUNET_SCHEDULER_add_after (sock->write_task,
549                                       &destroy_continuation, sock);
550     return;
551   }
552   if (0 != (sock->ccs & COCO_RECEIVE_AGAIN))
553   {
554     sock->ccs |= COCO_DESTROY_CONTINUATION;
555     return;
556   }
557   if (sock->sock != NULL)
558   {
559 #if DEBUG_CONNECTION
560     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Shutting down socket (%p)\n", sock);
561 #endif
562     if (sock->persist != GNUNET_YES)
563     {
564       if ((GNUNET_YES != GNUNET_NETWORK_socket_shutdown (sock->sock, SHUT_RDWR))
565           && (errno != ENOTCONN) && (errno != ECONNRESET))
566         GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "shutdown");
567     }
568   }
569   if (sock->read_task != GNUNET_SCHEDULER_NO_TASK)
570   {
571     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == sock->destroy_task);
572     sock->destroy_task
573         = GNUNET_SCHEDULER_add_after (sock->read_task,
574                                       &destroy_continuation, sock);
575     return;
576   }
577 #if DEBUG_CONNECTION
578   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Destroy actually runs (%p)!\n", sock);
579 #endif
580   while (NULL != (pos = sock->ap_head))
581   {
582     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
583     GNUNET_SCHEDULER_cancel (pos->task);
584     GNUNET_CONTAINER_DLL_remove (sock->ap_head, sock->ap_tail, pos);
585     GNUNET_free (pos);
586   }
587   GNUNET_assert (sock->nth.timeout_task == GNUNET_SCHEDULER_NO_TASK);
588   GNUNET_assert (sock->ccs == COCO_NONE);
589   if (NULL != (notify = sock->nth.notify_ready))
590   {
591     sock->nth.notify_ready = NULL;
592     notify (sock->nth.notify_ready_cls, 0, NULL);
593   }
594
595   if (sock->sock != NULL)
596   {
597     if (sock->persist != GNUNET_YES)
598       GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock->sock));
599     else
600       GNUNET_free (sock->sock); /* at least no memory leak (we deliberately
601                                  * leak the socket in this special case) ... */
602   }
603   GNUNET_free_non_null (sock->addr);
604   GNUNET_free_non_null (sock->hostname);
605   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == sock->destroy_task);
606 #if DEBUG_CONNECTION
607   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
608               "Freeing memory of connection %p.\n", sock);
609 #endif
610   GNUNET_free (sock->write_buffer);
611   GNUNET_free (sock);
612 }
613
614
615
616 /**
617  * See if we are now connected.  If not, wait longer for
618  * connect to succeed.  If connected, we should be able
619  * to write now as well, unless we timed out.
620  *
621  * @param cls our connection handle
622  * @param tc task context describing why we are here
623  */
624 static void
625 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
626
627
628 /**
629  * We've failed for good to establish a connection.
630  *
631  * @param h the connection we tried to establish
632  */
633 static void
634 connect_fail_continuation (struct GNUNET_CONNECTION_Handle *h)
635 {
636 #if DEBUG_CONNECTION
637   GNUNET_log ((0 != strncmp (h->hostname,
638                              "localhost:",
639                              10))
640               ? GNUNET_ERROR_TYPE_INFO
641               : GNUNET_ERROR_TYPE_WARNING,
642               _
643               ("Failed to establish TCP connection to `%s:%u', no further addresses to try.\n"),
644               h->hostname, h->port);
645 #endif
646   /* connect failed / timed out */
647   GNUNET_break (h->ap_head == NULL);
648   GNUNET_break (h->ap_tail == NULL);
649   GNUNET_break (h->dns_active == GNUNET_NO);
650   GNUNET_break (h->sock == NULL);
651
652   /* trigger jobs that used to wait on "connect_task" */
653   if (0 != (h->ccs & COCO_RECEIVE_AGAIN))
654   {
655 #if DEBUG_CONNECTION
656     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
657                 "connect_fail_continuation triggers receive_again (%p)\n", h);
658 #endif
659     h->ccs -= COCO_RECEIVE_AGAIN;
660     h->read_task = GNUNET_SCHEDULER_add_now (&receive_again, h);
661   }
662   if (0 != (h->ccs & COCO_TRANSMIT_READY))
663   {
664 #if DEBUG_CONNECTION
665     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
666                 "connect_fail_continuation cancels timeout_task, triggers transmit_ready (%p)\n",
667                 h);
668 #endif
669     GNUNET_assert (h->nth.timeout_task != GNUNET_SCHEDULER_NO_TASK);
670     GNUNET_SCHEDULER_cancel (h->nth.timeout_task);
671     h->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
672     h->ccs -= COCO_TRANSMIT_READY;
673     GNUNET_assert (h->nth.notify_ready != NULL);
674     GNUNET_assert (h->write_task == GNUNET_SCHEDULER_NO_TASK);
675     h->write_task = GNUNET_SCHEDULER_add_now (&transmit_ready, h);
676   }
677   if (0 != (h->ccs & COCO_DESTROY_CONTINUATION))
678   {
679 #if DEBUG_CONNECTION
680     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
681                 "connect_fail_continuation runs destroy_continuation (%p)\n",
682                 h);
683 #endif
684     h->ccs -= COCO_DESTROY_CONTINUATION;
685     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == h->destroy_task);
686     h->destroy_task = GNUNET_SCHEDULER_add_now (&destroy_continuation, h);
687   }
688 }
689
690
691 /**
692  * We've succeeded in establishing a connection.
693  *
694  * @param h the connection we tried to establish
695  */
696 static void
697 connect_success_continuation (struct GNUNET_CONNECTION_Handle *h)
698 {
699 #if DEBUG_CONNECTION
700   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
701               "Connection to `%s' succeeded! (%p)\n",
702               GNUNET_a2s (h->addr, h->addrlen), h);
703 #endif
704   /* trigger jobs that waited for the connection */
705   if (0 != (h->ccs & COCO_RECEIVE_AGAIN))
706   {
707 #if DEBUG_CONNECTION
708     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
709                 "connect_success_continuation runs receive_again (%p)\n", h);
710 #endif
711     h->ccs -= COCO_RECEIVE_AGAIN;
712     h->read_task = GNUNET_SCHEDULER_add_now (&receive_again, h);
713   }
714   if (0 != (h->ccs & COCO_TRANSMIT_READY))
715   {
716 #if DEBUG_CONNECTION
717     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
718                 "connect_success_continuation runs transmit_ready, cancels timeout_task (%p)\n",
719                 h);
720 #endif
721     GNUNET_assert (h->nth.timeout_task != GNUNET_SCHEDULER_NO_TASK);
722     GNUNET_SCHEDULER_cancel (h->nth.timeout_task);
723     h->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
724     h->ccs -= COCO_TRANSMIT_READY;
725     GNUNET_assert (h->write_task == GNUNET_SCHEDULER_NO_TASK);
726     GNUNET_assert (h->nth.notify_ready != NULL);
727     h->write_task =
728         GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
729                                         (h->nth.transmit_timeout), h->sock,
730                                         &transmit_ready, h);
731   }
732   if (0 != (h->ccs & COCO_DESTROY_CONTINUATION))
733   {
734 #if DEBUG_CONNECTION
735     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
736                 "connect_success_continuation runs destroy_continuation (%p)\n",
737                 h);
738 #endif
739     h->ccs -= COCO_DESTROY_CONTINUATION;
740     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == h->destroy_task);
741     h->destroy_task = GNUNET_SCHEDULER_add_now (&destroy_continuation, h);
742   }
743 }
744
745
746 /**
747  * Scheduler let us know that we're either ready to write on the
748  * socket OR connect timed out.  Do the right thing.
749  *
750  * @param cls the "struct AddressProbe*" with the address that we are probing
751  * @param tc success or failure info about the connect attempt.
752  */
753 static void
754 connect_probe_continuation (void *cls,
755                             const struct GNUNET_SCHEDULER_TaskContext *tc)
756 {
757   struct AddressProbe *ap = cls;
758   struct GNUNET_CONNECTION_Handle *h = ap->h;
759   struct AddressProbe *pos;
760   int error;
761   socklen_t len;
762
763   GNUNET_assert (ap->sock != NULL);
764   GNUNET_CONTAINER_DLL_remove (h->ap_head, h->ap_tail, ap);
765   len = sizeof (error);
766   errno = 0;
767   error = 0;
768   if ((0 == (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) ||
769       (GNUNET_OK !=
770        GNUNET_NETWORK_socket_getsockopt (ap->sock, SOL_SOCKET, SO_ERROR,
771                                          &error, &len)) || (error != 0))
772   {
773     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (ap->sock));
774     GNUNET_free (ap);
775     if ((NULL == h->ap_head) && (h->dns_active == GNUNET_NO))
776       connect_fail_continuation (h);
777     return;
778   }
779   GNUNET_assert (h->sock == NULL);
780   h->sock = ap->sock;
781   GNUNET_assert (h->addr == NULL);
782   h->addr = GNUNET_malloc (ap->addrlen);
783   memcpy (h->addr, ap->addr, ap->addrlen);
784   h->addrlen = ap->addrlen;
785   GNUNET_free (ap);
786   /* cancel all other attempts */
787   while (NULL != (pos = h->ap_head))
788   {
789     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
790     GNUNET_SCHEDULER_cancel (pos->task);
791     GNUNET_CONTAINER_DLL_remove (h->ap_head, h->ap_tail, pos);
792     GNUNET_free (pos);
793   }
794   connect_success_continuation (h);
795 }
796
797
798 /**
799  * Try to establish a socket connection given the specified address.
800  * This function is called by the resolver once we have a DNS reply.
801  *
802  * @param cls our "struct GNUNET_CONNECTION_Handle *"
803  * @param addr address to try, NULL for "last call"
804  * @param addrlen length of addr
805  */
806 static void
807 try_connect_using_address (void *cls,
808                            const struct sockaddr *addr, socklen_t addrlen)
809 {
810   struct GNUNET_CONNECTION_Handle *h = cls;
811   struct AddressProbe *ap;
812   struct GNUNET_TIME_Relative delay;
813
814   if (addr == NULL)
815   {
816     h->dns_active = NULL;
817     if (NULL == h->ap_head)
818       connect_fail_continuation (h);
819     return;
820   }
821   if (h->sock != NULL)
822     return;                     /* already connected */
823   GNUNET_assert (h->addr == NULL);
824   /* try to connect */
825 #if DEBUG_CONNECTION
826   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
827               "Trying to connect using address `%s:%u/%s:%u'\n",
828               h->hostname, h->port, GNUNET_a2s (addr, addrlen), h->port);
829 #endif
830   ap = GNUNET_malloc (sizeof (struct AddressProbe) + addrlen);
831   ap->addr = (const struct sockaddr *) &ap[1];
832   memcpy (&ap[1], addr, addrlen);
833   ap->addrlen = addrlen;
834   ap->h = h;
835
836   switch (ap->addr->sa_family)
837   {
838   case AF_INET:
839     ((struct sockaddr_in *) ap->addr)->sin_port = htons (h->port);
840     break;
841   case AF_INET6:
842     ((struct sockaddr_in6 *) ap->addr)->sin6_port = htons (h->port);
843     break;
844   default:
845     GNUNET_break (0);
846     GNUNET_free (ap);
847     return;                     /* not supported by us */
848   }
849   ap->sock = GNUNET_NETWORK_socket_create (ap->addr->sa_family, SOCK_STREAM, 0);
850   if (ap->sock == NULL)
851   {
852     GNUNET_free (ap);
853     return;                     /* not supported by OS */
854   }
855 #if DEBUG_CONNECTION
856   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
857               _("Trying to connect to `%s' (%p)\n"),
858               GNUNET_a2s (ap->addr, ap->addrlen), h);
859 #endif
860   if ((GNUNET_OK != GNUNET_NETWORK_socket_connect (ap->sock,
861                                                    ap->addr,
862                                                    ap->addrlen)) &&
863       (errno != EINPROGRESS))
864   {
865     /* maybe refused / unsupported address, try next */
866     GNUNET_log_strerror (GNUNET_ERROR_TYPE_INFO, "connect");
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 = GNUNET_TIME_relative_min (delay,
875                                       GNUNET_TIME_absolute_get_remaining
876                                       (h->nth.transmit_timeout));
877   if (h->receiver != NULL)
878     delay = GNUNET_TIME_relative_min (delay,
879                                       GNUNET_TIME_absolute_get_remaining
880                                       (h->receive_timeout));
881   ap->task =
882       GNUNET_SCHEDULER_add_write_net (delay, ap->sock,
883                                       &connect_probe_continuation, ap);
884 }
885
886
887 /**
888  * Create a socket handle by (asynchronously) connecting to a host.
889  * This function returns immediately, even if the connection has not
890  * yet been established.  This function only creates TCP connections.
891  *
892  * @param cfg configuration to use
893  * @param hostname name of the host to connect to
894  * @param port port to connect to
895  * @return the socket handle
896  */
897 struct GNUNET_CONNECTION_Handle *
898 GNUNET_CONNECTION_create_from_connect (const struct
899                                        GNUNET_CONFIGURATION_Handle *cfg,
900                                        const char *hostname, uint16_t port)
901 {
902   struct GNUNET_CONNECTION_Handle *ret;
903
904   GNUNET_assert (0 < strlen (hostname));        /* sanity check */
905   ret = GNUNET_malloc (sizeof (struct GNUNET_CONNECTION_Handle));
906   ret->cfg = cfg;
907   ret->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
908   ret->write_buffer = GNUNET_malloc (ret->write_buffer_size);
909   ret->port = port;
910   ret->hostname = GNUNET_strdup (hostname);
911   ret->dns_active = GNUNET_RESOLVER_ip_get (ret->hostname,
912                                             AF_UNSPEC,
913                                             GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT,
914                                             &try_connect_using_address, ret);
915   return ret;
916 }
917
918
919 /**
920  * Create a socket handle by connecting to a UNIX domain service.
921  * This function returns immediately, even if the connection has not
922  * yet been established.  This function only creates UNIX connections.
923  *
924  * @param cfg configuration to use
925  * @param unixpath path to connect to
926  * @return the socket handle, NULL on systems without UNIX support
927  */
928 struct GNUNET_CONNECTION_Handle *
929 GNUNET_CONNECTION_create_from_connect_to_unixpath (const struct
930                                                    GNUNET_CONFIGURATION_Handle
931                                                    *cfg, const char *unixpath)
932 {
933 #ifdef AF_UNIX
934   struct GNUNET_CONNECTION_Handle *ret;
935   struct sockaddr_un *un;
936   size_t slen;
937
938   GNUNET_assert (0 < strlen (unixpath));        /* sanity check */
939   un = GNUNET_malloc (sizeof (struct sockaddr_un));
940   un->sun_family = AF_UNIX;
941   slen = strlen (unixpath);
942   if (slen >= sizeof (un->sun_path))
943     slen = sizeof (un->sun_path) - 1;
944   memcpy (un->sun_path, unixpath, slen);
945   un->sun_path[slen] = '\0';
946   slen = sizeof (struct sockaddr_un);
947 #if HAVE_SOCKADDR_IN_SIN_LEN
948   un->sun_len = (u_char) slen;
949 #endif
950 #if LINUX
951   un->sun_path[0] = '\0';
952 #endif
953   ret = GNUNET_malloc (sizeof (struct GNUNET_CONNECTION_Handle));
954   ret->cfg = cfg;
955   ret->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
956   ret->write_buffer = GNUNET_malloc (ret->write_buffer_size);
957   ret->port = 0;
958   ret->hostname = NULL;
959   ret->addr = (struct sockaddr *) un;
960   ret->addrlen = slen;
961   ret->sock = GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_STREAM, 0);
962   if (NULL == ret->sock)
963   {
964     GNUNET_free (ret->addr);
965     GNUNET_free (ret->write_buffer);
966     GNUNET_free (ret);
967     return NULL;
968   }
969   if (GNUNET_OK != GNUNET_NETWORK_socket_connect (ret->sock,
970                                                   ret->addr, ret->addrlen))
971   {
972     /* Just return; we expect everything to work eventually so don't fail HARD */
973     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (ret->sock));
974     ret->sock = NULL;
975     return ret;
976   }
977   connect_success_continuation (ret);
978   return ret;
979 #else
980   return NULL;
981 #endif
982 }
983
984
985 /**
986  * Create a socket handle by (asynchronously) connecting to a host.
987  * This function returns immediately, even if the connection has not
988  * yet been established.  This function only creates TCP connections.
989  *
990  * @param af_family address family to use
991  * @param serv_addr server address
992  * @param addrlen length of server address
993  * @return the socket handle
994  */
995 struct GNUNET_CONNECTION_Handle *
996 GNUNET_CONNECTION_create_from_sockaddr (int af_family,
997                                         const struct sockaddr *serv_addr,
998                                         socklen_t addrlen)
999 {
1000   struct GNUNET_NETWORK_Handle *s;
1001   struct GNUNET_CONNECTION_Handle *ret;
1002
1003
1004   s = GNUNET_NETWORK_socket_create (af_family, SOCK_STREAM, 0);
1005   if (s == NULL)
1006   {
1007     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING |
1008                          GNUNET_ERROR_TYPE_BULK, "socket");
1009     return NULL;
1010   }
1011   if ((GNUNET_OK != GNUNET_NETWORK_socket_connect (s, serv_addr, addrlen))
1012       && (errno != EINPROGRESS))
1013   {
1014     /* maybe refused / unsupported address, try next */
1015     GNUNET_log_strerror (GNUNET_ERROR_TYPE_INFO, "connect");
1016     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1017                 _("Attempt to connect to `%s' failed\n"),
1018                 GNUNET_a2s (serv_addr, addrlen));
1019     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (s));
1020     return NULL;
1021   }
1022   ret = GNUNET_CONNECTION_create_from_existing (s);
1023   ret->addr = GNUNET_malloc (addrlen);
1024   memcpy (ret->addr, serv_addr, addrlen);
1025   ret->addrlen = addrlen;
1026 #if DEBUG_CONNECTION
1027   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1028               _("Trying to connect to `%s' (%p)\n"),
1029               GNUNET_a2s (serv_addr, addrlen), ret);
1030 #endif
1031   return ret;
1032 }
1033
1034
1035 /**
1036  * Check if socket is valid (no fatal errors have happened so far).
1037  * Note that a socket that is still trying to connect is considered
1038  * valid.
1039  *
1040  * @param sock socket to check
1041  * @return GNUNET_YES if valid, GNUNET_NO otherwise
1042  */
1043 int
1044 GNUNET_CONNECTION_check (struct GNUNET_CONNECTION_Handle *sock)
1045 {
1046   if ((sock->ap_head != NULL) || (sock->dns_active != NULL))
1047     return GNUNET_YES;          /* still trying to connect */
1048   return (sock->sock == NULL) ? GNUNET_NO : GNUNET_YES;
1049 }
1050
1051
1052 /**
1053  * Close the socket and free associated resources. Pending
1054  * transmissions may be completed or dropped depending on the
1055  * arguments.   If a receive call is pending and should 
1056  * NOT be completed, 'GNUNET_CONNECTION_receive_cancel'
1057  * should be called explicitly first.
1058  *
1059  * @param sock socket to destroy
1060  * @param finish_pending_write should pending writes be completed or aborted?
1061  *        (this applies to transmissions where the data has already been
1062  *        read from the application; all other transmissions should be
1063  *        aborted using 'GNUNET_CONNECTION_notify_transmit_ready_cancel').
1064  */
1065 void
1066 GNUNET_CONNECTION_destroy (struct GNUNET_CONNECTION_Handle *sock,
1067                            int finish_pending_write)
1068 {
1069   if (GNUNET_NO == finish_pending_write)
1070   {
1071     if (sock->write_task != GNUNET_SCHEDULER_NO_TASK)
1072     {
1073       GNUNET_SCHEDULER_cancel (sock->write_task);
1074       sock->write_task = GNUNET_SCHEDULER_NO_TASK;
1075       sock->write_buffer_off = 0;
1076     }
1077     sock->nth.notify_ready = NULL;
1078   }
1079   if ((sock->write_buffer_off == 0) && (sock->dns_active != NULL))
1080   {
1081     GNUNET_RESOLVER_request_cancel (sock->dns_active);
1082     sock->dns_active = NULL;
1083   }
1084
1085   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == sock->destroy_task);
1086   sock->destroy_task = GNUNET_SCHEDULER_add_now (&destroy_continuation, sock);
1087 }
1088
1089
1090 /**
1091  * Tell the receiver callback that a timeout was reached.
1092  */
1093 static void
1094 signal_timeout (struct GNUNET_CONNECTION_Handle *sh)
1095 {
1096   GNUNET_CONNECTION_Receiver receiver;
1097
1098 #if DEBUG_CONNECTION
1099   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1100               "Network signals time out to receiver (%p)!\n", sh);
1101 #endif
1102   GNUNET_assert (NULL != (receiver = sh->receiver));
1103   sh->receiver = NULL;
1104   receiver (sh->receiver_cls, NULL, 0, NULL, 0, 0);
1105 }
1106
1107
1108 /**
1109  * Tell the receiver callback that we had an IO error.
1110  */
1111 static void
1112 signal_error (struct GNUNET_CONNECTION_Handle *sh, int errcode)
1113 {
1114   GNUNET_CONNECTION_Receiver receiver;
1115
1116   GNUNET_assert (NULL != (receiver = sh->receiver));
1117   sh->receiver = NULL;
1118   receiver (sh->receiver_cls, NULL, 0, sh->addr, sh->addrlen, errcode);
1119 }
1120
1121
1122 /**
1123  * This function is called once we either timeout
1124  * or have data ready to read.
1125  */
1126 static void
1127 receive_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1128 {
1129   struct GNUNET_CONNECTION_Handle *sh = cls;
1130   struct GNUNET_TIME_Absolute now;
1131   char buffer[sh->max];
1132   ssize_t ret;
1133   GNUNET_CONNECTION_Receiver receiver;
1134
1135   sh->read_task = GNUNET_SCHEDULER_NO_TASK;
1136   if ((GNUNET_YES == sh->ignore_shutdown) &&
1137       (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)))
1138   {
1139     /* ignore shutdown request, go again immediately */
1140 #if DEBUG_CONNECTION
1141     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1142                 "Ignoring shutdown signal per configuration\n");
1143 #endif
1144     sh->read_task =
1145         GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1146                                        (sh->receive_timeout), sh->sock,
1147                                        &receive_ready, sh);
1148     return;
1149   }
1150   now = GNUNET_TIME_absolute_get ();
1151   if ((now.abs_value > sh->receive_timeout.abs_value) ||
1152       (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT)) ||
1153       (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)))
1154   {
1155 #if DEBUG_CONNECTION
1156     if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1157       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1158                   "Receive from `%s' encounters error: time out by %llums... (%p)\n",
1159                   GNUNET_a2s (sh->addr, sh->addrlen),
1160                   GNUNET_TIME_absolute_get_duration (sh->receive_timeout).
1161                   rel_value, sh);
1162 #endif
1163     signal_timeout (sh);
1164     return;
1165   }
1166   if (sh->sock == NULL)
1167   {
1168     /* connect failed for good */
1169 #if DEBUG_CONNECTION
1170     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1171                 "Receive encounters error, socket closed... (%p)\n", sh);
1172 #endif
1173     signal_error (sh, ECONNREFUSED);
1174     return;
1175   }
1176   GNUNET_assert (GNUNET_NETWORK_fdset_isset (tc->read_ready, sh->sock));
1177 RETRY:
1178   ret = GNUNET_NETWORK_socket_recv (sh->sock, buffer, sh->max);
1179   if (ret == -1)
1180   {
1181     if (errno == EINTR)
1182       goto RETRY;
1183 #if DEBUG_CONNECTION
1184     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1185                 "Error receiving: %s\n", STRERROR (errno));
1186 #endif
1187     signal_error (sh, errno);
1188     return;
1189   }
1190 #if DEBUG_CONNECTION
1191   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1192               "receive_ready read %u/%u bytes from `%s' (%p)!\n",
1193               (unsigned int) ret,
1194               sh->max, GNUNET_a2s (sh->addr, sh->addrlen), sh);
1195 #endif
1196   GNUNET_assert (NULL != (receiver = sh->receiver));
1197   sh->receiver = NULL;
1198   receiver (sh->receiver_cls, buffer, ret, sh->addr, sh->addrlen, 0);
1199 }
1200
1201
1202 /**
1203  * This function is called after establishing a connection either has
1204  * succeeded or timed out.  Note that it is possible that the attempt
1205  * timed out and that we're immediately retrying.  If we are retrying,
1206  * we need to wait again (or timeout); if we succeeded, we need to
1207  * wait for data (or timeout).
1208  *
1209  * @param cls our connection handle
1210  * @param tc task context describing why we are here
1211  */
1212 static void
1213 receive_again (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1214 {
1215   struct GNUNET_CONNECTION_Handle *sh = cls;
1216   struct GNUNET_TIME_Absolute now;
1217
1218   sh->read_task = GNUNET_SCHEDULER_NO_TASK;
1219   if (sh->sock == NULL)
1220   {
1221     /* not connected and no longer trying */
1222 #if DEBUG_CONNECTION
1223     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1224                 "Receive encounters error, socket closed (%p)...\n", sh);
1225 #endif
1226     signal_error (sh, ECONNREFUSED);
1227     return;
1228   }
1229   now = GNUNET_TIME_absolute_get ();
1230   if ((now.abs_value > sh->receive_timeout.abs_value) ||
1231       (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)))
1232   {
1233 #if DEBUG_CONNECTION
1234     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1235                 "Receive encounters error: time out (%p)...\n", sh);
1236 #endif
1237     signal_timeout (sh);
1238     return;
1239   }
1240   GNUNET_assert (sh->sock != NULL);
1241   /* connect succeeded, wait for data! */
1242   sh->read_task =
1243       GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1244                                      (sh->receive_timeout), sh->sock,
1245                                      &receive_ready, sh);
1246 }
1247
1248
1249 /**
1250  * Receive data from the given socket.  Note that this function will
1251  * call "receiver" asynchronously using the scheduler.  It will
1252  * "immediately" return.  Note that there MUST only be one active
1253  * receive call per socket at any given point in time (so do not
1254  * call receive again until the receiver callback has been invoked).
1255  *
1256  * @param sock socket handle
1257  * @param max maximum number of bytes to read
1258  * @param timeout maximum amount of time to wait (use -1 for "forever")
1259  * @param receiver function to call with received data
1260  * @param receiver_cls closure for receiver
1261  */
1262 void
1263 GNUNET_CONNECTION_receive (struct GNUNET_CONNECTION_Handle *sock,
1264                            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,
1362              &sock->write_buffer[sock->write_buffer_pos], 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 = notify (sock->nth.notify_ready_cls,
1369                  avail, &sock->write_buffer[sock->write_buffer_off]);
1370   GNUNET_assert (size <= avail);
1371   sock->write_buffer_off += size;
1372   return GNUNET_YES;
1373 }
1374
1375
1376 /**
1377  * Task invoked by the scheduler when a call to transmit
1378  * is timing out (we never got enough buffer space to call
1379  * the callback function before the specified timeout
1380  * expired).
1381  *
1382  * This task notifies the client about the timeout.
1383  *
1384  * @param cls the 'struct GNUNET_CONNECTION_Handle'
1385  * @param tc scheduler context
1386  */
1387 static void
1388 transmit_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1389 {
1390   struct GNUNET_CONNECTION_Handle *sock = cls;
1391   GNUNET_CONNECTION_TransmitReadyNotify notify;
1392
1393 #if DEBUG_CONNECTION
1394   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "transmit_timeout running (%p)\n", sock);
1395 #endif
1396   sock->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
1397 #if DEBUG_CONNECTION
1398   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1399               "Transmit to `%s:%u/%s' fails, time out reached (%p).\n",
1400               sock->hostname,
1401               sock->port, GNUNET_a2s (sock->addr, sock->addrlen), sock);
1402 #endif
1403   GNUNET_assert (0 != (sock->ccs & COCO_TRANSMIT_READY));
1404   sock->ccs -= COCO_TRANSMIT_READY;     /* remove request */
1405   notify = sock->nth.notify_ready;
1406   sock->nth.notify_ready = NULL;
1407   notify (sock->nth.notify_ready_cls, 0, NULL);
1408 }
1409
1410
1411 /**
1412  * Task invoked by the scheduler when we failed to connect
1413  * at the time of being asked to transmit.
1414  *
1415  * This task notifies the client about the error.
1416  *
1417  * @param cls the 'struct GNUNET_CONNECTION_Handle'
1418  * @param tc scheduler context
1419  */
1420 static void
1421 connect_error (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1422 {
1423   struct GNUNET_CONNECTION_Handle *sock = cls;
1424   GNUNET_CONNECTION_TransmitReadyNotify notify;
1425
1426 #if DEBUG_CONNECTION
1427   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1428               "Transmission request of size %u fails (%s/%u), connection failed (%p).\n",
1429               sock->nth.notify_size, sock->hostname, sock->port, sock);
1430 #endif
1431   sock->write_task = GNUNET_SCHEDULER_NO_TASK;
1432   notify = sock->nth.notify_ready;
1433   sock->nth.notify_ready = NULL;
1434   notify (sock->nth.notify_ready_cls, 0, NULL);
1435 }
1436
1437
1438 /**
1439  * FIXME
1440  *
1441  * @param sock FIXME
1442  */
1443 static void
1444 transmit_error (struct GNUNET_CONNECTION_Handle *sock)
1445 {
1446   GNUNET_CONNECTION_TransmitReadyNotify notify;
1447
1448   if (NULL != sock->sock)
1449   {
1450     GNUNET_NETWORK_socket_shutdown (sock->sock, SHUT_RDWR);
1451     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock->sock));
1452     sock->sock = NULL;
1453   }
1454   if (sock->read_task != GNUNET_SCHEDULER_NO_TASK)
1455   {
1456     GNUNET_SCHEDULER_cancel (sock->read_task);
1457     sock->read_task = GNUNET_SCHEDULER_NO_TASK;
1458     signal_timeout (sock);
1459     return;
1460   }
1461   if (sock->nth.notify_ready == NULL)
1462     return;                     /* nobody to tell about it */
1463   notify = sock->nth.notify_ready;
1464   sock->nth.notify_ready = NULL;
1465   notify (sock->nth.notify_ready_cls, 0, NULL);
1466 }
1467
1468
1469 /**
1470  * See if we are now connected.  If not, wait longer for
1471  * connect to succeed.  If connected, we should be able
1472  * to write now as well, unless we timed out.
1473  *
1474  * @param cls our connection handle
1475  * @param tc task context describing why we are here
1476  */
1477 static void
1478 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1479 {
1480   struct GNUNET_CONNECTION_Handle *sock = cls;
1481   GNUNET_CONNECTION_TransmitReadyNotify notify;
1482   ssize_t ret;
1483   size_t have;
1484
1485 #if DEBUG_CONNECTION
1486   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "transmit_ready running (%p).\n", sock);
1487 #endif
1488   GNUNET_assert (sock->write_task != GNUNET_SCHEDULER_NO_TASK);
1489   sock->write_task = GNUNET_SCHEDULER_NO_TASK;
1490   GNUNET_assert (sock->nth.timeout_task == GNUNET_SCHEDULER_NO_TASK);
1491   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1492   {
1493     if (sock->ignore_shutdown == GNUNET_YES)
1494       goto SCHEDULE_WRITE;      /* ignore shutdown, go again immediately */
1495 #if DEBUG_CONNECTION
1496     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1497                 "Transmit to `%s' fails, shutdown happened (%p).\n",
1498                 GNUNET_a2s (sock->addr, sock->addrlen), sock);
1499 #endif
1500     notify = sock->nth.notify_ready;
1501     if (NULL != notify)
1502     {
1503       sock->nth.notify_ready = NULL;
1504       notify (sock->nth.notify_ready_cls, 0, NULL);
1505     }
1506     return;
1507   }
1508   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1509   {
1510 #if DEBUG_CONNECTION
1511     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1512                 "Transmit to `%s' fails, time out reached (%p).\n",
1513                 GNUNET_a2s (sock->addr, sock->addrlen), sock);
1514 #endif
1515     notify = sock->nth.notify_ready;
1516     GNUNET_assert (NULL != notify);
1517     sock->nth.notify_ready = NULL;
1518     notify (sock->nth.notify_ready_cls, 0, NULL);
1519     return;
1520   }
1521   GNUNET_assert (NULL != sock->sock);
1522   if (tc->write_ready == NULL)
1523   {
1524     /* special circumstances (in particular,
1525      * PREREQ_DONE after connect): not yet ready to write,
1526      * but no "fatal" error either.  Hence retry.  */
1527     goto SCHEDULE_WRITE;
1528   }
1529   if (!GNUNET_NETWORK_fdset_isset (tc->write_ready, sock->sock))
1530   {
1531 #if DEBUG_CONNECTION
1532     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1533                 _
1534                 ("Could not satisfy pending transmission request, socket closed or connect failed (%p).\n"),
1535                 sock);
1536 #endif
1537     transmit_error (sock);
1538     return;                     /* connect failed for good, we're finished */
1539   }
1540   GNUNET_assert (sock->write_buffer_off >= sock->write_buffer_pos);
1541   if ((sock->nth.notify_ready != NULL) &&
1542       (sock->write_buffer_size < sock->nth.notify_size))
1543   {
1544     sock->write_buffer = GNUNET_realloc (sock->write_buffer,
1545                                          sock->nth.notify_size);
1546     sock->write_buffer_size = sock->nth.notify_size;
1547   }
1548   process_notify (sock);
1549   have = sock->write_buffer_off - sock->write_buffer_pos;
1550   if (have == 0)
1551   {
1552     /* no data ready for writing, terminate write loop */
1553     return;
1554   }
1555   GNUNET_assert (have <= sock->write_buffer_size);
1556   GNUNET_assert (have + sock->write_buffer_pos <= sock->write_buffer_size);
1557   GNUNET_assert (sock->write_buffer_pos <= sock->write_buffer_size);
1558 RETRY:
1559   ret = GNUNET_NETWORK_socket_send (sock->sock,
1560                                     &sock->write_buffer[sock->write_buffer_pos],
1561                                     have);
1562   if (ret == -1)
1563   {
1564     if (errno == EINTR)
1565       goto RETRY;
1566 #if 0
1567     int en = errno;
1568
1569     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1570                 _("Failed to send to `%s': %s\n"),
1571                 GNUNET_a2s (sock->addr, sock->addrlen), STRERROR (en));
1572 #endif
1573 #if DEBUG_CONNECTION
1574     GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG, "send");
1575 #endif
1576     transmit_error (sock);
1577     return;
1578   }
1579 #if DEBUG_CONNECTION
1580   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1581               "transmit_ready transmitted %u/%u bytes to `%s' (%p)\n",
1582               (unsigned int) ret,
1583               have, GNUNET_a2s (sock->addr, sock->addrlen), sock);
1584 #endif
1585   sock->write_buffer_pos += ret;
1586   if (sock->write_buffer_pos == sock->write_buffer_off)
1587   {
1588     /* transmitted all pending data */
1589     sock->write_buffer_pos = 0;
1590     sock->write_buffer_off = 0;
1591   }
1592   if ((sock->write_buffer_off == 0) && (NULL == sock->nth.notify_ready))
1593     return;                     /* all data sent! */
1594   /* not done writing, schedule more */
1595 SCHEDULE_WRITE:
1596 #if DEBUG_CONNECTION
1597   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1598               "Re-scheduling transmit_ready (more to do) (%p).\n", sock);
1599 #endif
1600   have = sock->write_buffer_off - sock->write_buffer_pos;
1601   GNUNET_assert ((sock->nth.notify_ready != NULL) || (have > 0));
1602   if (sock->write_task == GNUNET_SCHEDULER_NO_TASK)
1603     sock->write_task =
1604         GNUNET_SCHEDULER_add_write_net ((sock->nth.notify_ready == NULL)
1605                                         ? GNUNET_TIME_UNIT_FOREVER_REL
1606                                         :
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
1629                                          *sock, 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) &&
1651       (sock->ap_head == NULL) && (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,
1664                 "Scheduling transmit_ready (%p).\n", 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 = GNUNET_SCHEDULER_add_delayed (timeout,
1680                                                            &transmit_timeout,
1681                                                            sock);
1682   }
1683   return &sock->nth;
1684 }
1685
1686
1687 /**
1688  * Cancel the specified transmission-ready notification.
1689  *
1690  * @param th notification to cancel
1691  */
1692 void
1693 GNUNET_CONNECTION_notify_transmit_ready_cancel (struct
1694                                                 GNUNET_CONNECTION_TransmitHandle
1695                                                 *h)
1696 {
1697   GNUNET_assert (h->notify_ready != NULL);
1698   if (0 != (h->sh->ccs & COCO_TRANSMIT_READY))
1699   {
1700 #if DEBUG_CONNECTION
1701     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1702                 "notify_transmit_ready_cancel cancels timeout_task (%p)\n", h);
1703 #endif
1704     GNUNET_SCHEDULER_cancel (h->timeout_task);
1705     h->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1706     h->sh->ccs -= COCO_TRANSMIT_READY;
1707   }
1708   else
1709   {
1710     if (h->sh->write_task != GNUNET_SCHEDULER_NO_TASK)
1711     {
1712       GNUNET_SCHEDULER_cancel (h->sh->write_task);
1713       h->sh->write_task = GNUNET_SCHEDULER_NO_TASK;
1714     }
1715   }
1716   h->notify_ready = NULL;
1717 }
1718
1719 /* end of connection.c */