9769c3cba08b4852fc8046d61f101ffd55207ab5
[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       GNUNET_free (ret->addr);
970       GNUNET_free (ret->write_buffer);
971       GNUNET_free (ret);
972       return NULL;
973     }
974   connect_success_continuation (ret);
975   return ret;
976 #else
977   return NULL;
978 #endif
979 }
980
981
982 /**
983  * Create a socket handle by (asynchronously) connecting to a host.
984  * This function returns immediately, even if the connection has not
985  * yet been established.  This function only creates TCP connections.
986  *
987  * @param af_family address family to use
988  * @param serv_addr server address
989  * @param addrlen length of server address
990  * @return the socket handle
991  */
992 struct GNUNET_CONNECTION_Handle *
993 GNUNET_CONNECTION_create_from_sockaddr (int af_family,
994                                         const struct sockaddr *serv_addr,
995                                         socklen_t addrlen)
996 {
997   struct GNUNET_NETWORK_Handle *s;
998   struct GNUNET_CONNECTION_Handle *ret;
999
1000
1001   s = GNUNET_NETWORK_socket_create (af_family, SOCK_STREAM, 0);
1002   if (s == NULL)
1003     {
1004       GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING |
1005                            GNUNET_ERROR_TYPE_BULK, "socket");
1006       return NULL;
1007     }
1008   if ((GNUNET_OK != GNUNET_NETWORK_socket_connect (s, serv_addr, addrlen))
1009       && (errno != EINPROGRESS))
1010     {
1011       /* maybe refused / unsupported address, try next */
1012       GNUNET_log_strerror (GNUNET_ERROR_TYPE_INFO, "connect");
1013       GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (s));
1014       return NULL;
1015     }
1016   ret = GNUNET_CONNECTION_create_from_existing (s);
1017   ret->addr = GNUNET_malloc (addrlen);
1018   memcpy (ret->addr, serv_addr, addrlen);
1019   ret->addrlen = addrlen;
1020 #if DEBUG_CONNECTION
1021   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1022               _("Trying to connect to `%s' (%p)\n"),
1023               GNUNET_a2s (serv_addr, addrlen), ret);
1024 #endif
1025   return ret;
1026 }
1027
1028
1029 /**
1030  * Check if socket is valid (no fatal errors have happened so far).
1031  * Note that a socket that is still trying to connect is considered
1032  * valid.
1033  *
1034  * @param sock socket to check
1035  * @return GNUNET_YES if valid, GNUNET_NO otherwise
1036  */
1037 int
1038 GNUNET_CONNECTION_check (struct GNUNET_CONNECTION_Handle *sock)
1039 {
1040   if ((sock->ap_head != NULL) || (sock->dns_active != NULL))
1041     return GNUNET_YES;          /* still trying to connect */
1042   return (sock->sock == NULL) ? GNUNET_NO : GNUNET_YES;
1043 }
1044
1045
1046 /**
1047  * Close the socket and free associated resources. Pending
1048  * transmissions may be completed or dropped depending on the
1049  * arguments.   If a receive call is pending and should 
1050  * NOT be completed, 'GNUNET_CONNECTION_receive_cancel'
1051  * should be called explicitly first.
1052  *
1053  * @param sock socket to destroy
1054  * @param finish_pending_write should pending writes be completed or aborted?
1055  *        (this applies to transmissions where the data has already been
1056  *        read from the application; all other transmissions should be
1057  *        aborted using 'GNUNET_CONNECTION_notify_transmit_ready_cancel').
1058  */
1059 void
1060 GNUNET_CONNECTION_destroy (struct GNUNET_CONNECTION_Handle *sock,
1061                            int finish_pending_write)
1062 {
1063   if (GNUNET_NO == finish_pending_write)
1064     {
1065       if (sock->write_task != GNUNET_SCHEDULER_NO_TASK)
1066         {
1067           GNUNET_SCHEDULER_cancel (sock->write_task);
1068           sock->write_task = GNUNET_SCHEDULER_NO_TASK;
1069           sock->write_buffer_off = 0;
1070         }
1071     }
1072   if ((sock->write_buffer_off == 0) && (sock->dns_active != NULL))
1073     {
1074       GNUNET_RESOLVER_request_cancel (sock->dns_active);
1075       sock->dns_active = NULL;
1076     }
1077
1078   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == sock->destroy_task);
1079   sock->destroy_task 
1080     = GNUNET_SCHEDULER_add_now (&destroy_continuation, sock);
1081 }
1082
1083
1084 /**
1085  * Tell the receiver callback that a timeout was reached.
1086  */
1087 static void
1088 signal_timeout (struct GNUNET_CONNECTION_Handle *sh)
1089 {
1090   GNUNET_CONNECTION_Receiver receiver;
1091
1092 #if DEBUG_CONNECTION
1093   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1094               "Network signals time out to receiver (%p)!\n", sh);
1095 #endif
1096   GNUNET_assert (NULL != (receiver = sh->receiver));
1097   sh->receiver = NULL;
1098   receiver (sh->receiver_cls, NULL, 0, NULL, 0, 0);
1099 }
1100
1101
1102 /**
1103  * Tell the receiver callback that we had an IO error.
1104  */
1105 static void
1106 signal_error (struct GNUNET_CONNECTION_Handle *sh, int errcode)
1107 {
1108   GNUNET_CONNECTION_Receiver receiver;
1109   GNUNET_assert (NULL != (receiver = sh->receiver));
1110   sh->receiver = NULL;
1111   receiver (sh->receiver_cls, NULL, 0, sh->addr, sh->addrlen, errcode);
1112 }
1113
1114
1115 /**
1116  * This function is called once we either timeout
1117  * or have data ready to read.
1118  */
1119 static void
1120 receive_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1121 {
1122   struct GNUNET_CONNECTION_Handle *sh = cls;
1123   struct GNUNET_TIME_Absolute now;
1124   char buffer[sh->max];
1125   ssize_t ret;
1126   GNUNET_CONNECTION_Receiver receiver;
1127
1128   sh->read_task = GNUNET_SCHEDULER_NO_TASK;
1129   if ( (GNUNET_YES == sh->ignore_shutdown) &&
1130        (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))) 
1131     {
1132       /* ignore shutdown request, go again immediately */
1133 #if DEBUG_CONNECTION
1134       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1135                   "Ignoring shutdown signal per configuration\n");
1136 #endif
1137       sh->read_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1138                                                      (sh->receive_timeout),
1139                                                      sh->sock,
1140                                                      &receive_ready, sh);
1141       return;
1142     }
1143   now = GNUNET_TIME_absolute_get ();
1144   if ((now.abs_value > sh->receive_timeout.abs_value) ||
1145       (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT)) ||
1146       (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)))
1147     {
1148 #if DEBUG_CONNECTION
1149       if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1150         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1151                     "Receive from `%s' encounters error: time out by %llums... (%p)\n",
1152                     GNUNET_a2s (sh->addr, sh->addrlen),
1153                     GNUNET_TIME_absolute_get_duration (sh->receive_timeout).
1154                     rel_value, sh);
1155 #endif
1156       signal_timeout (sh);
1157       return;
1158     }
1159   if (sh->sock == NULL)
1160     {
1161       /* connect failed for good */
1162 #if DEBUG_CONNECTION
1163       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1164                   "Receive encounters error, socket closed... (%p)\n", sh);
1165 #endif
1166       signal_error (sh, ECONNREFUSED);
1167       return;
1168     }
1169   GNUNET_assert (GNUNET_NETWORK_fdset_isset (tc->read_ready, sh->sock));
1170 RETRY:
1171   ret = GNUNET_NETWORK_socket_recv (sh->sock, buffer, sh->max);
1172   if (ret == -1)
1173     {
1174       if (errno == EINTR)
1175         goto RETRY;
1176 #if DEBUG_CONNECTION
1177       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1178                   "Error receiving: %s\n", STRERROR (errno));
1179 #endif
1180       signal_error (sh, errno);
1181       return;
1182     }
1183 #if DEBUG_CONNECTION
1184   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1185               "receive_ready read %u/%u bytes from `%s' (%p)!\n",
1186               (unsigned int) ret,
1187               sh->max, GNUNET_a2s (sh->addr, sh->addrlen), sh);
1188 #endif
1189   GNUNET_assert (NULL != (receiver = sh->receiver));
1190   sh->receiver = NULL;
1191   receiver (sh->receiver_cls, buffer, ret, sh->addr, sh->addrlen, 0);
1192 }
1193
1194
1195 /**
1196  * This function is called after establishing a connection either has
1197  * succeeded or timed out.  Note that it is possible that the attempt
1198  * timed out and that we're immediately retrying.  If we are retrying,
1199  * we need to wait again (or timeout); if we succeeded, we need to
1200  * wait for data (or timeout).
1201  *
1202  * @param cls our connection handle
1203  * @param tc task context describing why we are here
1204  */
1205 static void
1206 receive_again (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1207 {
1208   struct GNUNET_CONNECTION_Handle *sh = cls;
1209   struct GNUNET_TIME_Absolute now;
1210
1211   sh->read_task = GNUNET_SCHEDULER_NO_TASK;
1212   if (sh->sock == NULL)
1213     {
1214       /* not connected and no longer trying */
1215 #if DEBUG_CONNECTION
1216       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1217                   "Receive encounters error, socket closed (%p)...\n", sh);
1218 #endif
1219       signal_error (sh, ECONNREFUSED);
1220       return;
1221     }
1222   now = GNUNET_TIME_absolute_get ();
1223   if ((now.abs_value > sh->receive_timeout.abs_value) ||
1224       (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)))
1225     {
1226 #if DEBUG_CONNECTION
1227       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1228                   "Receive encounters error: time out (%p)...\n", sh);
1229 #endif
1230       signal_timeout (sh);
1231       return;
1232     }
1233   GNUNET_assert (sh->sock != NULL);
1234   /* connect succeeded, wait for data! */
1235   sh->read_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1236                                                  (sh->receive_timeout),
1237                                                  sh->sock,
1238                                                  &receive_ready, sh);
1239 }
1240
1241
1242 /**
1243  * Receive data from the given socket.  Note that this function will
1244  * call "receiver" asynchronously using the scheduler.  It will
1245  * "immediately" return.  Note that there MUST only be one active
1246  * receive call per socket at any given point in time (so do not
1247  * call receive again until the receiver callback has been invoked).
1248  *
1249  * @param sock socket handle
1250  * @param max maximum number of bytes to read
1251  * @param timeout maximum amount of time to wait (use -1 for "forever")
1252  * @param receiver function to call with received data
1253  * @param receiver_cls closure for receiver
1254  */
1255 void
1256 GNUNET_CONNECTION_receive (struct GNUNET_CONNECTION_Handle *sock,
1257                            size_t max,
1258                            struct GNUNET_TIME_Relative timeout,
1259                            GNUNET_CONNECTION_Receiver receiver,
1260                            void *receiver_cls)
1261 {
1262   struct GNUNET_SCHEDULER_TaskContext tc;
1263
1264   GNUNET_assert ((sock->read_task == GNUNET_SCHEDULER_NO_TASK) &&
1265                  (0 == (sock->ccs & COCO_RECEIVE_AGAIN)) &&
1266                  (sock->receiver == NULL));
1267   sock->receiver = receiver;
1268   sock->receiver_cls = receiver_cls;
1269   sock->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1270   sock->max = max;
1271   if (sock->sock != NULL)
1272     {
1273       memset (&tc, 0, sizeof (tc));
1274       tc.reason = GNUNET_SCHEDULER_REASON_PREREQ_DONE;
1275       receive_again (sock, &tc);
1276       return;
1277     }
1278   if ((sock->dns_active == NULL) && (sock->ap_head == NULL))
1279     {
1280       receiver (receiver_cls, NULL, 0, NULL, 0, ETIMEDOUT);
1281       return;
1282     }
1283   sock->ccs += COCO_RECEIVE_AGAIN;
1284 }
1285
1286
1287 /**
1288  * Configure this connection to ignore shutdown signals.
1289  *
1290  * @param sock socket handle
1291  * @param do_ignore GNUNET_YES to ignore, GNUNET_NO to restore default
1292  */
1293 void
1294 GNUNET_CONNECTION_ignore_shutdown (struct GNUNET_CONNECTION_Handle *sock,
1295                                    int do_ignore)
1296 {
1297   sock->ignore_shutdown = do_ignore;
1298 }
1299
1300
1301 /**
1302  * Cancel receive job on the given socket.  Note that the
1303  * receiver callback must not have been called yet in order
1304  * for the cancellation to be valid.
1305  *
1306  * @param sock socket handle
1307  * @return closure of the original receiver callback closure
1308  */
1309 void *
1310 GNUNET_CONNECTION_receive_cancel (struct GNUNET_CONNECTION_Handle *sock)
1311 {
1312   if (sock->read_task != GNUNET_SCHEDULER_NO_TASK)
1313     {
1314       GNUNET_assert (sock == GNUNET_SCHEDULER_cancel (sock->read_task));
1315       sock->read_task = GNUNET_SCHEDULER_NO_TASK;
1316     }
1317   else
1318     {
1319       GNUNET_assert (0 != (sock->ccs & COCO_RECEIVE_AGAIN));
1320       sock->ccs -= COCO_RECEIVE_AGAIN;
1321     }
1322   sock->receiver = NULL;
1323   return sock->receiver_cls;
1324 }
1325
1326
1327 /**
1328  * Try to call the transmit notify method (check if we do
1329  * have enough space available first)!
1330  *
1331  * @param sock socket for which we should do this processing
1332  * @return GNUNET_YES if we were able to call notify
1333  */
1334 static int
1335 process_notify (struct GNUNET_CONNECTION_Handle *sock)
1336 {
1337   size_t used;
1338   size_t avail;
1339   size_t size;
1340   GNUNET_CONNECTION_TransmitReadyNotify notify;
1341
1342   GNUNET_assert (sock->write_task == GNUNET_SCHEDULER_NO_TASK);
1343   if (NULL == (notify = sock->nth.notify_ready))
1344     return GNUNET_NO;
1345   used = sock->write_buffer_off - sock->write_buffer_pos;
1346   avail = sock->write_buffer_size - used;
1347   size = sock->nth.notify_size;
1348   if (size > avail)
1349     return GNUNET_NO;
1350   sock->nth.notify_ready = NULL;
1351   if (sock->write_buffer_size - sock->write_buffer_off < size)
1352     {
1353       /* need to compact */
1354       memmove (sock->write_buffer,
1355                &sock->write_buffer[sock->write_buffer_pos], used);
1356       sock->write_buffer_off -= sock->write_buffer_pos;
1357       sock->write_buffer_pos = 0;
1358     }
1359   avail = sock->write_buffer_size - sock->write_buffer_off;
1360   GNUNET_assert (avail >= size);
1361   size = notify (sock->nth.notify_ready_cls,
1362                  avail,
1363                  &sock->write_buffer[sock->write_buffer_off]);
1364   GNUNET_assert (size <= avail);
1365   sock->write_buffer_off += size;
1366   return GNUNET_YES;
1367 }
1368
1369
1370 /**
1371  * Task invoked by the scheduler when a call to transmit
1372  * is timing out (we never got enough buffer space to call
1373  * the callback function before the specified timeout
1374  * expired).
1375  *
1376  * This task notifies the client about the timeout.
1377  *
1378  * @param cls the 'struct GNUNET_CONNECTION_Handle'
1379  * @param tc scheduler context
1380  */
1381 static void
1382 transmit_timeout (void *cls, 
1383                   const struct GNUNET_SCHEDULER_TaskContext *tc)
1384 {
1385   struct GNUNET_CONNECTION_Handle *sock = cls;
1386   GNUNET_CONNECTION_TransmitReadyNotify notify;
1387
1388 #if DEBUG_CONNECTION
1389   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1390               "transmit_timeout running (%p)\n", sock);
1391 #endif
1392   sock->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
1393 #if DEBUG_CONNECTION
1394   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1395               "Transmit to `%s:%u/%s' fails, time out reached (%p).\n",
1396               sock->hostname,
1397               sock->port, GNUNET_a2s (sock->addr, sock->addrlen), sock);
1398 #endif
1399   GNUNET_assert (0 != (sock->ccs & COCO_TRANSMIT_READY));
1400   sock->ccs -= COCO_TRANSMIT_READY;     /* remove request */
1401   notify = sock->nth.notify_ready;
1402   sock->nth.notify_ready = NULL;
1403   notify (sock->nth.notify_ready_cls, 0, NULL);
1404 }
1405
1406
1407 /**
1408  * Task invoked by the scheduler when we failed to connect
1409  * at the time of being asked to transmit.
1410  *
1411  * This task notifies the client about the error.
1412  *
1413  * @param cls the 'struct GNUNET_CONNECTION_Handle'
1414  * @param tc scheduler context
1415  */
1416 static void
1417 connect_error (void *cls, 
1418                const struct GNUNET_SCHEDULER_TaskContext *tc)
1419 {
1420   struct GNUNET_CONNECTION_Handle *sock = cls;
1421   GNUNET_CONNECTION_TransmitReadyNotify notify;
1422
1423   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1424               "Transmission request of size %u fails (%s/%u), connection failed (%p).\n",
1425               sock->nth.notify_size, 
1426               sock->hostname,
1427               sock->port,
1428               sock);
1429 #if DEBUG_CONNECTION
1430   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1431               "Transmission request of size %u fails, connection failed (%p).\n",
1432               sock->nth.notify_size, sock);
1433 #endif
1434   sock->write_task = GNUNET_SCHEDULER_NO_TASK;
1435   notify = sock->nth.notify_ready;
1436   sock->nth.notify_ready = NULL;
1437   notify (sock->nth.notify_ready_cls, 0, NULL);
1438 }
1439
1440
1441 /**
1442  * FIXME
1443  *
1444  * @param sock FIXME
1445  */
1446 static void
1447 transmit_error (struct GNUNET_CONNECTION_Handle *sock)
1448 {
1449   GNUNET_CONNECTION_TransmitReadyNotify notify;
1450
1451   if (NULL != sock->sock)
1452     {
1453       GNUNET_NETWORK_socket_shutdown (sock->sock, SHUT_RDWR);
1454       GNUNET_break (GNUNET_OK ==
1455                     GNUNET_NETWORK_socket_close (sock->sock));
1456       sock->sock = NULL;
1457     }
1458   if (sock->read_task != GNUNET_SCHEDULER_NO_TASK)
1459     {
1460       GNUNET_SCHEDULER_cancel (sock->read_task);
1461       sock->read_task = GNUNET_SCHEDULER_NO_TASK;
1462       signal_timeout (sock);
1463       return;
1464     }
1465   if (sock->nth.notify_ready == NULL)
1466     return;                     /* nobody to tell about it */
1467   notify = sock->nth.notify_ready;
1468   sock->nth.notify_ready = NULL;
1469   notify (sock->nth.notify_ready_cls, 0, NULL);
1470 }
1471
1472
1473 /**
1474  * See if we are now connected.  If not, wait longer for
1475  * connect to succeed.  If connected, we should be able
1476  * to write now as well, unless we timed out.
1477  *
1478  * @param cls our connection handle
1479  * @param tc task context describing why we are here
1480  */
1481 static void
1482 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1483 {
1484   struct GNUNET_CONNECTION_Handle *sock = cls;
1485   GNUNET_CONNECTION_TransmitReadyNotify notify;
1486   ssize_t ret;
1487   size_t have;
1488
1489 #if DEBUG_CONNECTION
1490   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1491               "transmit_ready running (%p).\n", sock);
1492 #endif
1493   GNUNET_assert (sock->write_task != GNUNET_SCHEDULER_NO_TASK);
1494   sock->write_task = GNUNET_SCHEDULER_NO_TASK;
1495   GNUNET_assert (sock->nth.timeout_task == GNUNET_SCHEDULER_NO_TASK);
1496   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)) 
1497     {
1498       if (sock->ignore_shutdown == GNUNET_YES)
1499         goto SCHEDULE_WRITE;    /* ignore shutdown, go again immediately */
1500 #if DEBUG_CONNECTION
1501       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1502                   "Transmit to `%s' fails, shutdown happened (%p).\n",
1503                   GNUNET_a2s (sock->addr, sock->addrlen), sock);
1504 #endif
1505       notify = sock->nth.notify_ready;
1506       sock->nth.notify_ready = NULL;
1507       notify (sock->nth.notify_ready_cls, 0, NULL);
1508       return;
1509     }
1510   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1511     {
1512 #if DEBUG_CONNECTION
1513       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1514                   "Transmit to `%s' fails, time out reached (%p).\n",
1515                   GNUNET_a2s (sock->addr, sock->addrlen), sock);
1516 #endif
1517       notify = sock->nth.notify_ready;
1518       sock->nth.notify_ready = NULL;
1519       notify (sock->nth.notify_ready_cls, 0, NULL);
1520       return;
1521     }
1522   GNUNET_assert (NULL != sock->sock);
1523   if (tc->write_ready == NULL)
1524     {
1525       /* special circumstances (in particular,
1526          PREREQ_DONE after connect): not yet ready to write,
1527          but no "fatal" error either.  Hence retry.  */
1528       goto SCHEDULE_WRITE;
1529     }
1530   if (!GNUNET_NETWORK_fdset_isset (tc->write_ready, sock->sock))
1531     {
1532 #if DEBUG_CONNECTION
1533       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1534                   _
1535                   ("Could not satisfy pending transmission request, socket closed or connect failed (%p).\n"),
1536                   sock);
1537 #endif
1538       transmit_error (sock);
1539       return;                   /* connect failed for good, we're finished */
1540     }
1541   GNUNET_assert (sock->write_buffer_off >= sock->write_buffer_pos);
1542   if ( (sock->nth.notify_ready != NULL) &&
1543        (sock->write_buffer_size < sock->nth.notify_size) )
1544     {
1545       sock->write_buffer = GNUNET_realloc(sock->write_buffer, 
1546                                           sock->nth.notify_size);
1547       sock->write_buffer_size = sock->nth.notify_size;
1548     }    
1549   process_notify (sock);
1550   have = sock->write_buffer_off - sock->write_buffer_pos;
1551   if (have == 0)
1552     {
1553       /* no data ready for writing, terminate write loop */
1554       return;
1555     }
1556   GNUNET_assert (have <= sock->write_buffer_size);
1557   GNUNET_assert (have + sock->write_buffer_pos <= sock->write_buffer_size);
1558   GNUNET_assert (sock->write_buffer_pos <= sock->write_buffer_size);
1559 RETRY:
1560   ret = GNUNET_NETWORK_socket_send (sock->sock,
1561                                     &sock->write_buffer[sock->
1562                                                         write_buffer_pos],
1563                                     have);
1564   if (ret == -1)
1565     {
1566       if (errno == EINTR)
1567         goto RETRY;
1568 #if 0
1569       int en = errno;
1570       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1571                   _("Failed to send to `%s': %s\n"),
1572                   GNUNET_a2s (sock->addr,
1573                               sock->addrlen),
1574                   STRERROR (en));
1575 #endif
1576 #if DEBUG_CONNECTION
1577       GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG, "send");
1578 #endif
1579       transmit_error (sock);
1580       return;
1581     }
1582 #if DEBUG_CONNECTION
1583   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1584               "transmit_ready transmitted %u/%u bytes to `%s' (%p)\n",
1585               (unsigned int) ret,
1586               have, GNUNET_a2s (sock->addr, sock->addrlen), sock);
1587 #endif
1588   sock->write_buffer_pos += ret;
1589   if (sock->write_buffer_pos == sock->write_buffer_off)
1590     {
1591       /* transmitted all pending data */
1592       sock->write_buffer_pos = 0;
1593       sock->write_buffer_off = 0;
1594     }
1595   if ((sock->write_buffer_off == 0) && (NULL == sock->nth.notify_ready))
1596     return;                     /* all data sent! */
1597   /* not done writing, schedule more */
1598 SCHEDULE_WRITE:
1599 #if DEBUG_CONNECTION
1600   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1601               "Re-scheduling transmit_ready (more to do) (%p).\n", sock);
1602 #endif
1603   if (sock->write_task == GNUNET_SCHEDULER_NO_TASK)
1604     sock->write_task =
1605       GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
1606                                       (sock->nth.transmit_timeout),
1607                                       sock->sock, &transmit_ready, sock);
1608 }
1609
1610
1611 /**
1612  * Ask the socket to call us once the specified number of bytes
1613  * are free in the transmission buffer.  May call the notify
1614  * method immediately if enough space is available.
1615  *
1616  * @param sock socket
1617  * @param size number of bytes to send
1618  * @param timeout after how long should we give up (and call
1619  *        notify with buf NULL and size 0)?
1620  * @param notify function to call
1621  * @param notify_cls closure for notify
1622  * @return non-NULL if the notify callback was queued,
1623  *         NULL if we are already going to notify someone else (busy)
1624  */
1625 struct GNUNET_CONNECTION_TransmitHandle *
1626 GNUNET_CONNECTION_notify_transmit_ready (struct GNUNET_CONNECTION_Handle
1627                                          *sock, size_t size,
1628                                          struct GNUNET_TIME_Relative timeout,
1629                                          GNUNET_CONNECTION_TransmitReadyNotify
1630                                          notify, void *notify_cls)
1631 {
1632   if (sock->nth.notify_ready != NULL)
1633     {
1634       GNUNET_break (0);
1635       return NULL;
1636     }
1637   GNUNET_assert (notify != NULL);
1638   GNUNET_assert (size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1639   GNUNET_assert (sock->write_buffer_off <= sock->write_buffer_size);
1640   GNUNET_assert (sock->write_buffer_pos <= sock->write_buffer_size);
1641   GNUNET_assert (sock->write_buffer_pos <= sock->write_buffer_off);
1642   sock->nth.notify_ready = notify;
1643   sock->nth.notify_ready_cls = notify_cls;
1644   sock->nth.sh = sock;
1645   sock->nth.notify_size = size;
1646   sock->nth.transmit_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1647   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == sock->nth.timeout_task);
1648   if ((sock->sock == NULL) &&
1649       (sock->ap_head == NULL) && (sock->dns_active == NULL))
1650     {
1651       if (sock->write_task != GNUNET_SCHEDULER_NO_TASK)
1652         GNUNET_SCHEDULER_cancel (sock->write_task);
1653       sock->write_task = GNUNET_SCHEDULER_add_now (&connect_error, sock);
1654       return &sock->nth;
1655     }
1656   if (GNUNET_SCHEDULER_NO_TASK != sock->write_task)
1657     return &sock->nth;
1658   if (sock->sock != NULL)
1659     {
1660 #if DEBUG_CONNECTION
1661       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1662                   "Scheduling transmit_ready (%p).\n", sock);
1663 #endif
1664       sock->write_task = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
1665                                                          (sock->nth.
1666                                                           transmit_timeout),
1667                                                          sock->sock,
1668                                                          &transmit_ready,
1669                                                          sock);
1670     }
1671   else
1672     {
1673 #if DEBUG_CONNECTION
1674       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1675                   "CCS-Scheduling transmit_ready, adding timeout task (%p).\n",
1676                   sock);
1677 #endif
1678       sock->ccs |= COCO_TRANSMIT_READY;
1679       sock->nth.timeout_task = GNUNET_SCHEDULER_add_delayed (timeout,
1680                                                              &transmit_timeout,
1681                                                              sock);
1682     }
1683   return &sock->nth;
1684 }
1685
1686
1687 /**
1688  * Cancel the specified transmission-ready
1689  * notification.
1690  */
1691 void
1692 GNUNET_CONNECTION_notify_transmit_ready_cancel (struct
1693                                                 GNUNET_CONNECTION_TransmitHandle
1694                                                 *h)
1695 {
1696   GNUNET_assert (h->notify_ready != NULL);
1697   if (0 != (h->sh->ccs & COCO_TRANSMIT_READY))
1698     {
1699 #if DEBUG_CONNECTION
1700       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1701                   "notify_transmit_ready_cancel cancels timeout_task (%p)\n",
1702                   h);
1703 #endif
1704       GNUNET_SCHEDULER_cancel (h->timeout_task);
1705       h->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1706       h->sh->ccs -= COCO_TRANSMIT_READY;
1707     }
1708   else
1709     {
1710       if (h->sh->write_task != GNUNET_SCHEDULER_NO_TASK)
1711         {
1712           GNUNET_SCHEDULER_cancel (h->sh->write_task);
1713           h->sh->write_task = GNUNET_SCHEDULER_NO_TASK;
1714         }
1715     }
1716   h->notify_ready = NULL;
1717 }
1718
1719 /* end of connection.c */