-removing 2nd argument from GNUNET_CLIENT_disconnect as it was virtually always GNUNE...
[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 /**
328  * Create a socket handle by boxing an existing OS socket.  The OS
329  * socket should henceforth be no longer used directly.
330  * GNUNET_socket_destroy will close it.
331  *
332  * @param osSocket existing socket to box
333  * @return the boxed socket handle
334  */
335 struct GNUNET_CONNECTION_Handle *
336 GNUNET_CONNECTION_create_from_existing (struct GNUNET_NETWORK_Handle *osSocket)
337 {
338   struct GNUNET_CONNECTION_Handle *ret;
339
340   ret = GNUNET_malloc (sizeof (struct GNUNET_CONNECTION_Handle));
341   ret->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
342   ret->write_buffer = GNUNET_malloc (ret->write_buffer_size);
343   ret->sock = osSocket;
344   return ret;
345 }
346
347
348 /**
349  * Create a socket 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 socket 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 *ret;
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   ret = GNUNET_malloc (sizeof (struct GNUNET_CONNECTION_Handle));
470   ret->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
471   ret->write_buffer = GNUNET_malloc (ret->write_buffer_size);
472   ret->addr = uaddr;
473   ret->addrlen = addrlen;
474   ret->sock = sock;
475   LOG (GNUNET_ERROR_TYPE_INFO, 
476        _("Accepting connection from `%s': %p\n"),
477        GNUNET_a2s (uaddr, addrlen), ret);
478   return ret;
479 }
480
481
482 /**
483  * Obtain the network address of the other party.
484  *
485  * @param sock 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 *sock,
492                                void **addr, size_t * addrlen)
493 {
494   if ((sock->addr == NULL) || (sock->addrlen == 0))
495     return GNUNET_NO;
496   *addr = GNUNET_malloc (sock->addrlen);
497   memcpy (*addr, sock->addr, sock->addrlen);
498   *addrlen = sock->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 *sock = cls;
528   GNUNET_CONNECTION_TransmitReadyNotify notify;
529   struct AddressProbe *pos;
530
531   sock->destroy_task = GNUNET_SCHEDULER_NO_TASK;
532   GNUNET_assert (sock->dns_active == NULL);
533   if (0 != (sock->ccs & COCO_TRANSMIT_READY))
534   {
535     LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroy waits for CCS-TR to be done (%p)\n",
536          sock);
537     sock->ccs |= COCO_DESTROY_CONTINUATION;
538     return;
539   }
540   if (sock->write_task != GNUNET_SCHEDULER_NO_TASK)
541   {
542     LOG (GNUNET_ERROR_TYPE_DEBUG,
543          "Destroy waits for write_task to be done (%p)\n", sock);
544     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == sock->destroy_task);
545     sock->destroy_task =
546         GNUNET_SCHEDULER_add_after (sock->write_task, &destroy_continuation,
547                                     sock);
548     return;
549   }
550   if (0 != (sock->ccs & COCO_RECEIVE_AGAIN))
551   {
552     sock->ccs |= COCO_DESTROY_CONTINUATION;
553     return;
554   }
555   if (sock->sock != NULL)
556   {
557     LOG (GNUNET_ERROR_TYPE_DEBUG, "Shutting down socket (%p)\n", sock);
558     if (sock->persist != GNUNET_YES)
559     {
560       if ((GNUNET_YES != GNUNET_NETWORK_socket_shutdown (sock->sock, SHUT_RDWR))
561           && (errno != ENOTCONN) && (errno != ECONNRESET))
562         LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "shutdown");
563     }
564   }
565   if (sock->read_task != GNUNET_SCHEDULER_NO_TASK)
566   {
567     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == sock->destroy_task);
568     sock->destroy_task =
569         GNUNET_SCHEDULER_add_after (sock->read_task, &destroy_continuation,
570                                     sock);
571     return;
572   }
573   LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroy actually runs (%p)!\n", sock);
574   while (NULL != (pos = sock->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 (sock->ap_head, sock->ap_tail, pos);
579     GNUNET_free (pos);
580   }
581   GNUNET_assert (sock->nth.timeout_task == GNUNET_SCHEDULER_NO_TASK);
582   GNUNET_assert (sock->ccs == COCO_NONE);
583   if (NULL != (notify = sock->nth.notify_ready))
584   {
585     sock->nth.notify_ready = NULL;
586     notify (sock->nth.notify_ready_cls, 0, NULL);
587   }
588
589   if (sock->sock != NULL)
590   {
591     if (sock->persist != GNUNET_YES)
592       GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock->sock));
593     else
594       GNUNET_free (sock->sock); /* at least no memory leak (we deliberately
595                                  * leak the socket in this special case) ... */
596   }
597   GNUNET_free_non_null (sock->addr);
598   GNUNET_free_non_null (sock->hostname);
599   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == sock->destroy_task);
600   LOG (GNUNET_ERROR_TYPE_DEBUG, "Freeing memory of connection %p.\n", sock);
601   GNUNET_free (sock->write_buffer);
602   GNUNET_free (sock);
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 h the connection we tried to establish
672  */
673 static void
674 connect_success_continuation (struct GNUNET_CONNECTION_Handle *h)
675 {
676   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connection to `%s' succeeded! (%p)\n",
677        GNUNET_a2s (h->addr, h->addrlen), h);
678   /* trigger jobs that waited for the connection */
679   if (0 != (h->ccs & COCO_RECEIVE_AGAIN))
680   {
681     LOG (GNUNET_ERROR_TYPE_DEBUG,
682          "connect_success_continuation runs receive_again (%p)\n", h);
683     h->ccs -= COCO_RECEIVE_AGAIN;
684     h->read_task = GNUNET_SCHEDULER_add_now (&receive_again, h);
685   }
686   if (0 != (h->ccs & COCO_TRANSMIT_READY))
687   {
688     LOG (GNUNET_ERROR_TYPE_DEBUG,
689          "connect_success_continuation runs transmit_ready, cancels timeout_task (%p)\n",
690          h);
691     GNUNET_assert (h->nth.timeout_task != GNUNET_SCHEDULER_NO_TASK);
692     GNUNET_SCHEDULER_cancel (h->nth.timeout_task);
693     h->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
694     h->ccs -= COCO_TRANSMIT_READY;
695     GNUNET_assert (h->write_task == GNUNET_SCHEDULER_NO_TASK);
696     GNUNET_assert (h->nth.notify_ready != NULL);
697     h->write_task =
698         GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
699                                         (h->nth.transmit_timeout), h->sock,
700                                         &transmit_ready, h);
701   }
702   if (0 != (h->ccs & COCO_DESTROY_CONTINUATION))
703   {
704     LOG (GNUNET_ERROR_TYPE_DEBUG,
705          "connect_success_continuation runs destroy_continuation (%p)\n", h);
706     h->ccs -= COCO_DESTROY_CONTINUATION;
707     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == h->destroy_task);
708     h->destroy_task = GNUNET_SCHEDULER_add_now (&destroy_continuation, h);
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 *h = ap->h;
726   struct AddressProbe *pos;
727   int error;
728   socklen_t len;
729
730   GNUNET_assert (ap->sock != NULL);
731   GNUNET_CONTAINER_DLL_remove (h->ap_head, h->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 == h->ap_head) && (h->dns_active == GNUNET_NO))
743       connect_fail_continuation (h);
744     return;
745   }
746   GNUNET_assert (h->sock == NULL);
747   h->sock = ap->sock;
748   GNUNET_assert (h->addr == NULL);
749   h->addr = GNUNET_malloc (ap->addrlen);
750   memcpy (h->addr, ap->addr, ap->addrlen);
751   h->addrlen = ap->addrlen;
752   GNUNET_free (ap);
753   /* cancel all other attempts */
754   while (NULL != (pos = h->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 (h->ap_head, h->ap_tail, pos);
759     GNUNET_free (pos);
760   }
761   connect_success_continuation (h);
762 }
763
764
765 /**
766  * Try to establish a socket 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 *h = cls;
778   struct AddressProbe *ap;
779   struct GNUNET_TIME_Relative delay;
780
781   if (addr == NULL)
782   {
783     h->dns_active = NULL;
784     if ((NULL == h->ap_head) && (NULL == h->sock))
785       connect_fail_continuation (h);
786     return;
787   }
788   if (h->sock != NULL)
789     return;                     /* already connected */
790   GNUNET_assert (h->addr == NULL);
791   /* try to connect */
792   LOG (GNUNET_ERROR_TYPE_DEBUG,
793        "Trying to connect using address `%s:%u/%s:%u'\n", h->hostname, h->port,
794        GNUNET_a2s (addr, addrlen), h->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->h = h;
800
801   switch (ap->addr->sa_family)
802   {
803   case AF_INET:
804     ((struct sockaddr_in *) ap->addr)->sin_port = htons (h->port);
805     break;
806   case AF_INET6:
807     ((struct sockaddr_in6 *) ap->addr)->sin6_port = htons (h->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), h);
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), h);
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 (h->ap_head, h->ap_tail, ap);
837   delay = GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT;
838   if (h->nth.notify_ready != NULL)
839     delay =
840         GNUNET_TIME_relative_min (delay,
841                                   GNUNET_TIME_absolute_get_remaining (h->
842                                                                       nth.transmit_timeout));
843   if (h->receiver != NULL)
844     delay =
845         GNUNET_TIME_relative_min (delay,
846                                   GNUNET_TIME_absolute_get_remaining
847                                   (h->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 socket 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 socket 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 *ret;
870
871   GNUNET_assert (0 < strlen (hostname));        /* sanity check */
872   ret = GNUNET_malloc (sizeof (struct GNUNET_CONNECTION_Handle));
873   ret->cfg = cfg;
874   ret->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
875   ret->write_buffer = GNUNET_malloc (ret->write_buffer_size);
876   ret->port = port;
877   ret->hostname = GNUNET_strdup (hostname);
878   ret->dns_active =
879       GNUNET_RESOLVER_ip_get (ret->hostname, AF_UNSPEC,
880                               GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT,
881                               &try_connect_using_address, ret);
882   return ret;
883 }
884
885
886 /**
887  * Create a socket 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 socket 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 *ret;
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   ret = GNUNET_malloc (sizeof (struct GNUNET_CONNECTION_Handle));
921   ret->cfg = cfg;
922   ret->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
923   ret->write_buffer = GNUNET_malloc (ret->write_buffer_size);
924   ret->port = 0;
925   ret->hostname = NULL;
926   ret->addr = (struct sockaddr *) un;
927   ret->addrlen = slen;
928   ret->sock = GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_STREAM, 0);
929   if (NULL == ret->sock)
930   {
931     GNUNET_free (ret->addr);
932     GNUNET_free (ret->write_buffer);
933     GNUNET_free (ret);
934     return NULL;
935   }
936   if (GNUNET_OK !=
937       GNUNET_NETWORK_socket_connect (ret->sock, ret->addr, ret->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 (ret->sock));
941     ret->sock = NULL;
942     return ret;
943   }
944   connect_success_continuation (ret);
945   return ret;
946 #else
947   return NULL;
948 #endif
949 }
950
951
952 /**
953  * Create a socket 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 socket 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 *ret;
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   ret = GNUNET_CONNECTION_create_from_existing (s);
988   ret->addr = GNUNET_malloc (addrlen);
989   memcpy (ret->addr, serv_addr, addrlen);
990   ret->addrlen = addrlen;
991   LOG (GNUNET_ERROR_TYPE_INFO, _("Trying to connect to `%s' (%p)\n"),
992        GNUNET_a2s (serv_addr, addrlen), ret);
993   return ret;
994 }
995
996
997 /**
998  * Check if socket is valid (no fatal errors have happened so far).
999  * Note that a socket that is still trying to connect is considered
1000  * valid.
1001  *
1002  * @param sock socket 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 socket and free associated resources. Pending
1016  * transmissions may be completed or dropped depending on the
1017  * arguments.   If a receive call is pending and should
1018  * NOT be completed, 'GNUNET_CONNECTION_receive_cancel'
1019  * should be called explicitly first.
1020  *
1021  * @param sock socket to destroy
1022  * @param finish_pending_write should pending writes be completed or aborted?
1023  *        (this applies to transmissions where the data has already been
1024  *        read from the application; all other transmissions should be
1025  *        aborted using 'GNUNET_CONNECTION_notify_transmit_ready_cancel').
1026  */
1027 void
1028 GNUNET_CONNECTION_destroy (struct GNUNET_CONNECTION_Handle *sock,
1029                            int finish_pending_write)
1030 {
1031   if (GNUNET_NO == finish_pending_write)
1032   {
1033     if (sock->write_task != GNUNET_SCHEDULER_NO_TASK)
1034     {
1035       GNUNET_SCHEDULER_cancel (sock->write_task);
1036       sock->write_task = GNUNET_SCHEDULER_NO_TASK;
1037       sock->write_buffer_off = 0;
1038     }
1039     sock->nth.notify_ready = NULL;
1040   }
1041   if ((sock->write_buffer_off == 0) && (sock->dns_active != NULL))
1042   {
1043     GNUNET_RESOLVER_request_cancel (sock->dns_active);
1044     sock->dns_active = NULL;
1045   }
1046   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == sock->destroy_task);
1047   sock->destroy_task = GNUNET_SCHEDULER_add_now (&destroy_continuation, sock);
1048 }
1049
1050
1051 /**
1052  * Tell the receiver callback that a timeout was reached.
1053  */
1054 static void
1055 signal_timeout (struct GNUNET_CONNECTION_Handle *sh)
1056 {
1057   GNUNET_CONNECTION_Receiver receiver;
1058
1059   LOG (GNUNET_ERROR_TYPE_DEBUG, "Network signals time out to receiver (%p)!\n",
1060        sh);
1061   GNUNET_assert (NULL != (receiver = sh->receiver));
1062   sh->receiver = NULL;
1063   receiver (sh->receiver_cls, NULL, 0, NULL, 0, 0);
1064 }
1065
1066
1067 /**
1068  * Tell the receiver callback that we had an IO error.
1069  */
1070 static void
1071 signal_error (struct GNUNET_CONNECTION_Handle *sh, int errcode)
1072 {
1073   GNUNET_CONNECTION_Receiver receiver;
1074
1075   GNUNET_assert (NULL != (receiver = sh->receiver));
1076   sh->receiver = NULL;
1077   receiver (sh->receiver_cls, NULL, 0, sh->addr, sh->addrlen, errcode);
1078 }
1079
1080
1081 /**
1082  * This function is called once we either timeout
1083  * or have data ready to read.
1084  */
1085 static void
1086 receive_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1087 {
1088   struct GNUNET_CONNECTION_Handle *sh = cls;
1089   struct GNUNET_TIME_Absolute now;
1090   char buffer[sh->max];
1091   ssize_t ret;
1092   GNUNET_CONNECTION_Receiver receiver;
1093
1094   sh->read_task = GNUNET_SCHEDULER_NO_TASK;
1095   if ((GNUNET_YES == sh->ignore_shutdown) &&
1096       (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)))
1097   {
1098     /* ignore shutdown request, go again immediately */
1099     LOG (GNUNET_ERROR_TYPE_DEBUG,
1100          "Ignoring shutdown signal per configuration\n");
1101     sh->read_task =
1102         GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1103                                        (sh->receive_timeout), sh->sock,
1104                                        &receive_ready, sh);
1105     return;
1106   }
1107   now = GNUNET_TIME_absolute_get ();
1108   if ((now.abs_value > sh->receive_timeout.abs_value) ||
1109       (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT)) ||
1110       (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)))
1111   {
1112     if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1113       LOG (GNUNET_ERROR_TYPE_DEBUG,
1114            "Receive from `%s' encounters error: time out by %llums... (%p)\n",
1115            GNUNET_a2s (sh->addr, sh->addrlen),
1116            GNUNET_TIME_absolute_get_duration (sh->receive_timeout).rel_value,
1117            sh);
1118     signal_timeout (sh);
1119     return;
1120   }
1121   if (sh->sock == NULL)
1122   {
1123     /* connect failed for good */
1124     LOG (GNUNET_ERROR_TYPE_DEBUG,
1125          "Receive encounters error, socket closed... (%p)\n", sh);
1126     signal_error (sh, ECONNREFUSED);
1127     return;
1128   }
1129   GNUNET_assert (GNUNET_NETWORK_fdset_isset (tc->read_ready, sh->sock));
1130 RETRY:
1131   ret = GNUNET_NETWORK_socket_recv (sh->sock, buffer, sh->max);
1132   if (ret == -1)
1133   {
1134     if (errno == EINTR)
1135       goto RETRY;
1136     LOG (GNUNET_ERROR_TYPE_DEBUG, "Error receiving: %s\n", STRERROR (errno));
1137     signal_error (sh, errno);
1138     return;
1139   }
1140   LOG (GNUNET_ERROR_TYPE_DEBUG,
1141        "receive_ready read %u/%u bytes from `%s' (%p)!\n", (unsigned int) ret,
1142        sh->max, GNUNET_a2s (sh->addr, sh->addrlen), sh);
1143   GNUNET_assert (NULL != (receiver = sh->receiver));
1144   sh->receiver = NULL;
1145   receiver (sh->receiver_cls, buffer, ret, sh->addr, sh->addrlen, 0);
1146 }
1147
1148
1149 /**
1150  * This function is called after establishing a connection either has
1151  * succeeded or timed out.  Note that it is possible that the attempt
1152  * timed out and that we're immediately retrying.  If we are retrying,
1153  * we need to wait again (or timeout); if we succeeded, we need to
1154  * wait for data (or timeout).
1155  *
1156  * @param cls our connection handle
1157  * @param tc task context describing why we are here
1158  */
1159 static void
1160 receive_again (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1161 {
1162   struct GNUNET_CONNECTION_Handle *sh = cls;
1163   struct GNUNET_TIME_Absolute now;
1164
1165   sh->read_task = GNUNET_SCHEDULER_NO_TASK;
1166   if (sh->sock == NULL)
1167   {
1168     /* not connected and no longer trying */
1169     LOG (GNUNET_ERROR_TYPE_DEBUG,
1170          "Receive encounters error, socket closed (%p)...\n", sh);
1171     signal_error (sh, ECONNREFUSED);
1172     return;
1173   }
1174   now = GNUNET_TIME_absolute_get ();
1175   if ((now.abs_value > sh->receive_timeout.abs_value) ||
1176       (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)))
1177   {
1178     LOG (GNUNET_ERROR_TYPE_DEBUG,
1179          "Receive encounters error: time out (%p)...\n", sh);
1180     signal_timeout (sh);
1181     return;
1182   }
1183   GNUNET_assert (sh->sock != NULL);
1184   /* connect succeeded, wait for data! */
1185   sh->read_task =
1186       GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1187                                      (sh->receive_timeout), sh->sock,
1188                                      &receive_ready, sh);
1189 }
1190
1191
1192 /**
1193  * Receive data from the given socket.  Note that this function will
1194  * call "receiver" asynchronously using the scheduler.  It will
1195  * "immediately" return.  Note that there MUST only be one active
1196  * receive call per socket at any given point in time (so do not
1197  * call receive again until the receiver callback has been invoked).
1198  *
1199  * @param sock socket handle
1200  * @param max maximum number of bytes to read
1201  * @param timeout maximum amount of time to wait (use -1 for "forever")
1202  * @param receiver function to call with received data
1203  * @param receiver_cls closure for receiver
1204  */
1205 void
1206 GNUNET_CONNECTION_receive (struct GNUNET_CONNECTION_Handle *sock, size_t max,
1207                            struct GNUNET_TIME_Relative timeout,
1208                            GNUNET_CONNECTION_Receiver receiver,
1209                            void *receiver_cls)
1210 {
1211   struct GNUNET_SCHEDULER_TaskContext tc;
1212
1213   GNUNET_assert ((sock->read_task == GNUNET_SCHEDULER_NO_TASK) &&
1214                  (0 == (sock->ccs & COCO_RECEIVE_AGAIN)) &&
1215                  (sock->receiver == NULL));
1216   sock->receiver = receiver;
1217   sock->receiver_cls = receiver_cls;
1218   sock->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1219   sock->max = max;
1220   if (sock->sock != NULL)
1221   {
1222     memset (&tc, 0, sizeof (tc));
1223     tc.reason = GNUNET_SCHEDULER_REASON_PREREQ_DONE;
1224     receive_again (sock, &tc);
1225     return;
1226   }
1227   if ((sock->dns_active == NULL) && (sock->ap_head == NULL))
1228   {
1229     receiver (receiver_cls, NULL, 0, NULL, 0, ETIMEDOUT);
1230     return;
1231   }
1232   sock->ccs += COCO_RECEIVE_AGAIN;
1233 }
1234
1235
1236 /**
1237  * Configure this connection to ignore shutdown signals.
1238  *
1239  * @param sock socket handle
1240  * @param do_ignore GNUNET_YES to ignore, GNUNET_NO to restore default
1241  */
1242 void
1243 GNUNET_CONNECTION_ignore_shutdown (struct GNUNET_CONNECTION_Handle *sock,
1244                                    int do_ignore)
1245 {
1246   sock->ignore_shutdown = do_ignore;
1247 }
1248
1249
1250 /**
1251  * Cancel receive job on the given socket.  Note that the
1252  * receiver callback must not have been called yet in order
1253  * for the cancellation to be valid.
1254  *
1255  * @param sock socket handle
1256  * @return closure of the original receiver callback closure
1257  */
1258 void *
1259 GNUNET_CONNECTION_receive_cancel (struct GNUNET_CONNECTION_Handle *sock)
1260 {
1261   if (sock->read_task != GNUNET_SCHEDULER_NO_TASK)
1262   {
1263     GNUNET_assert (sock == GNUNET_SCHEDULER_cancel (sock->read_task));
1264     sock->read_task = GNUNET_SCHEDULER_NO_TASK;
1265   }
1266   else
1267   {
1268     GNUNET_assert (0 != (sock->ccs & COCO_RECEIVE_AGAIN));
1269     sock->ccs -= COCO_RECEIVE_AGAIN;
1270   }
1271   sock->receiver = NULL;
1272   return sock->receiver_cls;
1273 }
1274
1275
1276 /**
1277  * Try to call the transmit notify method (check if we do
1278  * have enough space available first)!
1279  *
1280  * @param sock socket for which we should do this processing
1281  * @return GNUNET_YES if we were able to call notify
1282  */
1283 static int
1284 process_notify (struct GNUNET_CONNECTION_Handle *sock)
1285 {
1286   size_t used;
1287   size_t avail;
1288   size_t size;
1289   GNUNET_CONNECTION_TransmitReadyNotify notify;
1290
1291   GNUNET_assert (sock->write_task == GNUNET_SCHEDULER_NO_TASK);
1292   if (NULL == (notify = sock->nth.notify_ready))
1293     return GNUNET_NO;
1294   used = sock->write_buffer_off - sock->write_buffer_pos;
1295   avail = sock->write_buffer_size - used;
1296   size = sock->nth.notify_size;
1297   if (size > avail)
1298     return GNUNET_NO;
1299   sock->nth.notify_ready = NULL;
1300   if (sock->write_buffer_size - sock->write_buffer_off < size)
1301   {
1302     /* need to compact */
1303     memmove (sock->write_buffer, &sock->write_buffer[sock->write_buffer_pos],
1304              used);
1305     sock->write_buffer_off -= sock->write_buffer_pos;
1306     sock->write_buffer_pos = 0;
1307   }
1308   avail = sock->write_buffer_size - sock->write_buffer_off;
1309   GNUNET_assert (avail >= size);
1310   size =
1311       notify (sock->nth.notify_ready_cls, avail,
1312               &sock->write_buffer[sock->write_buffer_off]);
1313   GNUNET_assert (size <= avail);
1314   sock->write_buffer_off += size;
1315   return GNUNET_YES;
1316 }
1317
1318
1319 /**
1320  * Task invoked by the scheduler when a call to transmit
1321  * is timing out (we never got enough buffer space to call
1322  * the callback function before the specified timeout
1323  * expired).
1324  *
1325  * This task notifies the client about the timeout.
1326  *
1327  * @param cls the 'struct GNUNET_CONNECTION_Handle'
1328  * @param tc scheduler context
1329  */
1330 static void
1331 transmit_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1332 {
1333   struct GNUNET_CONNECTION_Handle *sock = cls;
1334   GNUNET_CONNECTION_TransmitReadyNotify notify;
1335
1336   sock->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
1337   LOG (GNUNET_ERROR_TYPE_DEBUG,
1338        "Transmit to `%s:%u/%s' fails, time out reached (%p).\n",
1339        sock->hostname,
1340        sock->port, GNUNET_a2s (sock->addr, sock->addrlen), sock);
1341   GNUNET_assert (0 != (sock->ccs & COCO_TRANSMIT_READY));
1342   sock->ccs -= COCO_TRANSMIT_READY;     /* remove request */
1343   notify = sock->nth.notify_ready;
1344   sock->nth.notify_ready = NULL;
1345   notify (sock->nth.notify_ready_cls, 0, NULL);
1346 }
1347
1348
1349 /**
1350  * Task invoked by the scheduler when we failed to connect
1351  * at the time of being asked to transmit.
1352  *
1353  * This task notifies the client about the error.
1354  *
1355  * @param cls the 'struct GNUNET_CONNECTION_Handle'
1356  * @param tc scheduler context
1357  */
1358 static void
1359 connect_error (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1360 {
1361   struct GNUNET_CONNECTION_Handle *sock = cls;
1362   GNUNET_CONNECTION_TransmitReadyNotify notify;
1363
1364   LOG (GNUNET_ERROR_TYPE_DEBUG,
1365        "Transmission request of size %u fails (%s/%u), connection failed (%p).\n",
1366        sock->nth.notify_size, sock->hostname, sock->port, sock);
1367   sock->write_task = GNUNET_SCHEDULER_NO_TASK;
1368   notify = sock->nth.notify_ready;
1369   sock->nth.notify_ready = NULL;
1370   notify (sock->nth.notify_ready_cls, 0, NULL);
1371 }
1372
1373
1374 /**
1375  * FIXME
1376  *
1377  * @param sock FIXME
1378  */
1379 static void
1380 transmit_error (struct GNUNET_CONNECTION_Handle *sock)
1381 {
1382   GNUNET_CONNECTION_TransmitReadyNotify notify;
1383
1384   if (NULL != sock->sock)
1385   {
1386     GNUNET_NETWORK_socket_shutdown (sock->sock, SHUT_RDWR);
1387     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock->sock));
1388     sock->sock = NULL;
1389     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == sock->write_task);
1390   }
1391   if (sock->read_task != GNUNET_SCHEDULER_NO_TASK)
1392   {
1393     GNUNET_SCHEDULER_cancel (sock->read_task);
1394     sock->read_task = GNUNET_SCHEDULER_NO_TASK;
1395     signal_timeout (sock);
1396     return;
1397   }
1398   if (sock->nth.notify_ready == NULL)
1399     return;                     /* nobody to tell about it */
1400   notify = sock->nth.notify_ready;
1401   sock->nth.notify_ready = NULL;
1402   notify (sock->nth.notify_ready_cls, 0, NULL);
1403 }
1404
1405
1406 /**
1407  * See if we are now connected.  If not, wait longer for
1408  * connect to succeed.  If connected, we should be able
1409  * to write now as well, unless we timed out.
1410  *
1411  * @param cls our connection handle
1412  * @param tc task context describing why we are here
1413  */
1414 static void
1415 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1416 {
1417   struct GNUNET_CONNECTION_Handle *sock = cls;
1418   GNUNET_CONNECTION_TransmitReadyNotify notify;
1419   ssize_t ret;
1420   size_t have;
1421
1422   LOG (GNUNET_ERROR_TYPE_DEBUG, "transmit_ready running (%p).\n", sock);
1423   GNUNET_assert (sock->write_task != GNUNET_SCHEDULER_NO_TASK);
1424   sock->write_task = GNUNET_SCHEDULER_NO_TASK;
1425   GNUNET_assert (sock->nth.timeout_task == GNUNET_SCHEDULER_NO_TASK);
1426   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1427   {
1428     if ((sock->ignore_shutdown == GNUNET_YES) && (NULL != sock->sock))
1429       goto SCHEDULE_WRITE;      /* ignore shutdown, go again immediately */
1430     LOG (GNUNET_ERROR_TYPE_DEBUG,
1431          "Transmit to `%s' fails, shutdown happened (%p).\n",
1432          GNUNET_a2s (sock->addr, sock->addrlen), sock);
1433     notify = sock->nth.notify_ready;
1434     if (NULL != notify)
1435     {
1436       sock->nth.notify_ready = NULL;
1437       notify (sock->nth.notify_ready_cls, 0, NULL);
1438     }
1439     return;
1440   }
1441   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1442   {
1443     LOG (GNUNET_ERROR_TYPE_DEBUG,
1444          "Transmit to `%s' fails, time out reached (%p).\n",
1445          GNUNET_a2s (sock->addr, sock->addrlen), sock);
1446     notify = sock->nth.notify_ready;
1447     GNUNET_assert (NULL != notify);
1448     sock->nth.notify_ready = NULL;
1449     notify (sock->nth.notify_ready_cls, 0, NULL);
1450     return;
1451   }
1452   GNUNET_assert (NULL != sock->sock);
1453   if (tc->write_ready == NULL)
1454   {
1455     /* special circumstances (in particular,
1456      * PREREQ_DONE after connect): not yet ready to write,
1457      * but no "fatal" error either.  Hence retry.  */
1458     goto SCHEDULE_WRITE;
1459   }
1460   if (!GNUNET_NETWORK_fdset_isset (tc->write_ready, sock->sock))
1461   {
1462     LOG (GNUNET_ERROR_TYPE_INFO,
1463          _
1464          ("Could not satisfy pending transmission request, socket closed or connect failed (%p).\n"),
1465          sock);
1466     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == sock->write_task);
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     if (GNUNET_SCHEDULER_NO_TASK != sock->write_task)
1499     {
1500       GNUNET_SCHEDULER_cancel (sock->write_task);
1501       sock->write_task = GNUNET_SCHEDULER_NO_TASK;
1502     }
1503     transmit_error (sock);
1504     return;
1505   }
1506   LOG (GNUNET_ERROR_TYPE_DEBUG,
1507        "transmit_ready transmitted %u/%u bytes to `%s' (%p)\n",
1508        (unsigned int) ret, have, GNUNET_a2s (sock->addr, sock->addrlen), sock);
1509   sock->write_buffer_pos += ret;
1510   if (sock->write_buffer_pos == sock->write_buffer_off)
1511   {
1512     /* transmitted all pending data */
1513     sock->write_buffer_pos = 0;
1514     sock->write_buffer_off = 0;
1515   }
1516   if ((sock->write_buffer_off == 0) && (NULL == sock->nth.notify_ready))
1517     return;                     /* all data sent! */
1518   /* not done writing, schedule more */
1519 SCHEDULE_WRITE:
1520   LOG (GNUNET_ERROR_TYPE_DEBUG,
1521        "Re-scheduling transmit_ready (more to do) (%p).\n", sock);
1522   have = sock->write_buffer_off - sock->write_buffer_pos;
1523   GNUNET_assert ((sock->nth.notify_ready != NULL) || (have > 0));
1524   if (sock->write_task == GNUNET_SCHEDULER_NO_TASK)
1525     sock->write_task =
1526         GNUNET_SCHEDULER_add_write_net ((sock->nth.notify_ready ==
1527                                          NULL) ? GNUNET_TIME_UNIT_FOREVER_REL :
1528                                         GNUNET_TIME_absolute_get_remaining
1529                                         (sock->nth.transmit_timeout),
1530                                         sock->sock, &transmit_ready, sock);
1531 }
1532
1533
1534 /**
1535  * Ask the socket to call us once the specified number of bytes
1536  * are free in the transmission buffer.  May call the notify
1537  * method immediately if enough space is available.
1538  *
1539  * @param sock socket
1540  * @param size number of bytes to send
1541  * @param timeout after how long should we give up (and call
1542  *        notify with buf NULL and size 0)?
1543  * @param notify function to call
1544  * @param notify_cls closure for notify
1545  * @return non-NULL if the notify callback was queued,
1546  *         NULL if we are already going to notify someone else (busy)
1547  */
1548 struct GNUNET_CONNECTION_TransmitHandle *
1549 GNUNET_CONNECTION_notify_transmit_ready (struct GNUNET_CONNECTION_Handle *sock,
1550                                          size_t size,
1551                                          struct GNUNET_TIME_Relative timeout,
1552                                          GNUNET_CONNECTION_TransmitReadyNotify
1553                                          notify, void *notify_cls)
1554 {
1555   if (sock->nth.notify_ready != NULL)
1556   {
1557     GNUNET_assert (0);
1558     return NULL;
1559   }
1560   GNUNET_assert (notify != NULL);
1561   GNUNET_assert (size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1562   GNUNET_assert (sock->write_buffer_off <= sock->write_buffer_size);
1563   GNUNET_assert (sock->write_buffer_pos <= sock->write_buffer_size);
1564   GNUNET_assert (sock->write_buffer_pos <= sock->write_buffer_off);
1565   sock->nth.notify_ready = notify;
1566   sock->nth.notify_ready_cls = notify_cls;
1567   sock->nth.sh = sock;
1568   sock->nth.notify_size = size;
1569   sock->nth.transmit_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1570   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == sock->nth.timeout_task);
1571   if ((sock->sock == NULL) && (sock->ap_head == NULL) &&
1572       (sock->dns_active == NULL))
1573   {
1574     if (sock->write_task != GNUNET_SCHEDULER_NO_TASK)
1575       GNUNET_SCHEDULER_cancel (sock->write_task);
1576     sock->write_task = GNUNET_SCHEDULER_add_now (&connect_error, sock);
1577     return &sock->nth;
1578   }
1579   if (GNUNET_SCHEDULER_NO_TASK != sock->write_task)
1580     return &sock->nth;
1581   if (sock->sock != NULL)
1582   {
1583     LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduling transmit_ready (%p).\n", sock);
1584     sock->write_task =
1585         GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
1586                                         (sock->nth.transmit_timeout),
1587                                         sock->sock, &transmit_ready, sock);
1588   }
1589   else
1590   {
1591     LOG (GNUNET_ERROR_TYPE_DEBUG,
1592          "CCS-Scheduling transmit_ready, adding timeout task (%p).\n", sock);
1593     sock->ccs |= COCO_TRANSMIT_READY;
1594     sock->nth.timeout_task =
1595         GNUNET_SCHEDULER_add_delayed (timeout, &transmit_timeout, sock);
1596   }
1597   return &sock->nth;
1598 }
1599
1600
1601 /**
1602  * Cancel the specified transmission-ready notification.
1603  *
1604  * @param th notification to cancel
1605  */
1606 void
1607 GNUNET_CONNECTION_notify_transmit_ready_cancel (struct
1608                                                 GNUNET_CONNECTION_TransmitHandle
1609                                                 *th)
1610 {
1611   GNUNET_assert (th->notify_ready != NULL);
1612   if (0 != (th->sh->ccs & COCO_TRANSMIT_READY))
1613   {
1614     LOG (GNUNET_ERROR_TYPE_DEBUG,
1615          "notify_transmit_ready_cancel cancels timeout_task (%p)\n", th);
1616     GNUNET_SCHEDULER_cancel (th->timeout_task);
1617     th->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1618     th->sh->ccs -= COCO_TRANSMIT_READY;
1619   }
1620   else
1621   {
1622     if (th->sh->write_task != GNUNET_SCHEDULER_NO_TASK)
1623     {
1624       GNUNET_SCHEDULER_cancel (th->sh->write_task);
1625       th->sh->write_task = GNUNET_SCHEDULER_NO_TASK;
1626     }
1627   }
1628   th->notify_ready = NULL;
1629 }
1630
1631 /* end of connection.c */