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