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