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