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