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