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