2953d9ca7f348127fd2352f2d6a636842c87dece
[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  */
1023 void
1024 GNUNET_CONNECTION_destroy (struct GNUNET_CONNECTION_Handle *sock)
1025 {
1026   int finish_pending_write = GNUNET_NO;
1027   if (GNUNET_NO == finish_pending_write)
1028   {
1029     if (sock->write_task != GNUNET_SCHEDULER_NO_TASK)
1030     {
1031       GNUNET_SCHEDULER_cancel (sock->write_task);
1032       sock->write_task = GNUNET_SCHEDULER_NO_TASK;
1033       sock->write_buffer_off = 0;
1034     }
1035     sock->nth.notify_ready = NULL;
1036   }
1037   if ((sock->write_buffer_off == 0) && (sock->dns_active != NULL))
1038   {
1039     GNUNET_RESOLVER_request_cancel (sock->dns_active);
1040     sock->dns_active = NULL;
1041   }
1042   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == sock->destroy_task);
1043   sock->destroy_task = GNUNET_SCHEDULER_add_now (&destroy_continuation, sock);
1044 }
1045
1046
1047 /**
1048  * Tell the receiver callback that a timeout was reached.
1049  */
1050 static void
1051 signal_timeout (struct GNUNET_CONNECTION_Handle *sh)
1052 {
1053   GNUNET_CONNECTION_Receiver receiver;
1054
1055   LOG (GNUNET_ERROR_TYPE_DEBUG, "Network signals time out to receiver (%p)!\n",
1056        sh);
1057   GNUNET_assert (NULL != (receiver = sh->receiver));
1058   sh->receiver = NULL;
1059   receiver (sh->receiver_cls, NULL, 0, NULL, 0, 0);
1060 }
1061
1062
1063 /**
1064  * Tell the receiver callback that we had an IO error.
1065  */
1066 static void
1067 signal_error (struct GNUNET_CONNECTION_Handle *sh, int errcode)
1068 {
1069   GNUNET_CONNECTION_Receiver receiver;
1070
1071   GNUNET_assert (NULL != (receiver = sh->receiver));
1072   sh->receiver = NULL;
1073   receiver (sh->receiver_cls, NULL, 0, sh->addr, sh->addrlen, errcode);
1074 }
1075
1076
1077 /**
1078  * This function is called once we either timeout
1079  * or have data ready to read.
1080  */
1081 static void
1082 receive_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1083 {
1084   struct GNUNET_CONNECTION_Handle *sh = cls;
1085   struct GNUNET_TIME_Absolute now;
1086   char buffer[sh->max];
1087   ssize_t ret;
1088   GNUNET_CONNECTION_Receiver receiver;
1089
1090   sh->read_task = GNUNET_SCHEDULER_NO_TASK;
1091   if ((GNUNET_YES == sh->ignore_shutdown) &&
1092       (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)))
1093   {
1094     /* ignore shutdown request, go again immediately */
1095     LOG (GNUNET_ERROR_TYPE_DEBUG,
1096          "Ignoring shutdown signal per configuration\n");
1097     sh->read_task =
1098         GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1099                                        (sh->receive_timeout), sh->sock,
1100                                        &receive_ready, sh);
1101     return;
1102   }
1103   now = GNUNET_TIME_absolute_get ();
1104   if ((now.abs_value > sh->receive_timeout.abs_value) ||
1105       (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT)) ||
1106       (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)))
1107   {
1108     if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1109       LOG (GNUNET_ERROR_TYPE_DEBUG,
1110            "Receive from `%s' encounters error: time out by %llums... (%p)\n",
1111            GNUNET_a2s (sh->addr, sh->addrlen),
1112            GNUNET_TIME_absolute_get_duration (sh->receive_timeout).rel_value,
1113            sh);
1114     signal_timeout (sh);
1115     return;
1116   }
1117   if (sh->sock == NULL)
1118   {
1119     /* connect failed for good */
1120     LOG (GNUNET_ERROR_TYPE_DEBUG,
1121          "Receive encounters error, socket closed... (%p)\n", sh);
1122     signal_error (sh, ECONNREFUSED);
1123     return;
1124   }
1125   GNUNET_assert (GNUNET_NETWORK_fdset_isset (tc->read_ready, sh->sock));
1126 RETRY:
1127   ret = GNUNET_NETWORK_socket_recv (sh->sock, buffer, sh->max);
1128   if (ret == -1)
1129   {
1130     if (errno == EINTR)
1131       goto RETRY;
1132     LOG (GNUNET_ERROR_TYPE_DEBUG, "Error receiving: %s\n", STRERROR (errno));
1133     signal_error (sh, errno);
1134     return;
1135   }
1136   LOG (GNUNET_ERROR_TYPE_DEBUG,
1137        "receive_ready read %u/%u bytes from `%s' (%p)!\n", (unsigned int) ret,
1138        sh->max, GNUNET_a2s (sh->addr, sh->addrlen), sh);
1139   GNUNET_assert (NULL != (receiver = sh->receiver));
1140   sh->receiver = NULL;
1141   receiver (sh->receiver_cls, buffer, ret, sh->addr, sh->addrlen, 0);
1142 }
1143
1144
1145 /**
1146  * This function is called after establishing a connection either has
1147  * succeeded or timed out.  Note that it is possible that the attempt
1148  * timed out and that we're immediately retrying.  If we are retrying,
1149  * we need to wait again (or timeout); if we succeeded, we need to
1150  * wait for data (or timeout).
1151  *
1152  * @param cls our connection handle
1153  * @param tc task context describing why we are here
1154  */
1155 static void
1156 receive_again (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1157 {
1158   struct GNUNET_CONNECTION_Handle *sh = cls;
1159   struct GNUNET_TIME_Absolute now;
1160
1161   sh->read_task = GNUNET_SCHEDULER_NO_TASK;
1162   if (sh->sock == NULL)
1163   {
1164     /* not connected and no longer trying */
1165     LOG (GNUNET_ERROR_TYPE_DEBUG,
1166          "Receive encounters error, socket closed (%p)...\n", sh);
1167     signal_error (sh, ECONNREFUSED);
1168     return;
1169   }
1170   now = GNUNET_TIME_absolute_get ();
1171   if ((now.abs_value > sh->receive_timeout.abs_value) ||
1172       (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)))
1173   {
1174     LOG (GNUNET_ERROR_TYPE_DEBUG,
1175          "Receive encounters error: time out (%p)...\n", sh);
1176     signal_timeout (sh);
1177     return;
1178   }
1179   GNUNET_assert (sh->sock != NULL);
1180   /* connect succeeded, wait for data! */
1181   sh->read_task =
1182       GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1183                                      (sh->receive_timeout), sh->sock,
1184                                      &receive_ready, sh);
1185 }
1186
1187
1188 /**
1189  * Receive data from the given socket.  Note that this function will
1190  * call "receiver" asynchronously using the scheduler.  It will
1191  * "immediately" return.  Note that there MUST only be one active
1192  * receive call per socket at any given point in time (so do not
1193  * call receive again until the receiver callback has been invoked).
1194  *
1195  * @param sock socket handle
1196  * @param max maximum number of bytes to read
1197  * @param timeout maximum amount of time to wait (use -1 for "forever")
1198  * @param receiver function to call with received data
1199  * @param receiver_cls closure for receiver
1200  */
1201 void
1202 GNUNET_CONNECTION_receive (struct GNUNET_CONNECTION_Handle *sock, size_t max,
1203                            struct GNUNET_TIME_Relative timeout,
1204                            GNUNET_CONNECTION_Receiver receiver,
1205                            void *receiver_cls)
1206 {
1207   struct GNUNET_SCHEDULER_TaskContext tc;
1208
1209   GNUNET_assert ((sock->read_task == GNUNET_SCHEDULER_NO_TASK) &&
1210                  (0 == (sock->ccs & COCO_RECEIVE_AGAIN)) &&
1211                  (sock->receiver == NULL));
1212   sock->receiver = receiver;
1213   sock->receiver_cls = receiver_cls;
1214   sock->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1215   sock->max = max;
1216   if (sock->sock != NULL)
1217   {
1218     memset (&tc, 0, sizeof (tc));
1219     tc.reason = GNUNET_SCHEDULER_REASON_PREREQ_DONE;
1220     receive_again (sock, &tc);
1221     return;
1222   }
1223   if ((sock->dns_active == NULL) && (sock->ap_head == NULL))
1224   {
1225     receiver (receiver_cls, NULL, 0, NULL, 0, ETIMEDOUT);
1226     return;
1227   }
1228   sock->ccs += COCO_RECEIVE_AGAIN;
1229 }
1230
1231
1232 /**
1233  * Configure this connection to ignore shutdown signals.
1234  *
1235  * @param sock socket handle
1236  * @param do_ignore GNUNET_YES to ignore, GNUNET_NO to restore default
1237  */
1238 void
1239 GNUNET_CONNECTION_ignore_shutdown (struct GNUNET_CONNECTION_Handle *sock,
1240                                    int do_ignore)
1241 {
1242   sock->ignore_shutdown = do_ignore;
1243 }
1244
1245
1246 /**
1247  * Cancel receive job on the given socket.  Note that the
1248  * receiver callback must not have been called yet in order
1249  * for the cancellation to be valid.
1250  *
1251  * @param sock socket handle
1252  * @return closure of the original receiver callback closure
1253  */
1254 void *
1255 GNUNET_CONNECTION_receive_cancel (struct GNUNET_CONNECTION_Handle *sock)
1256 {
1257   if (sock->read_task != GNUNET_SCHEDULER_NO_TASK)
1258   {
1259     GNUNET_assert (sock == GNUNET_SCHEDULER_cancel (sock->read_task));
1260     sock->read_task = GNUNET_SCHEDULER_NO_TASK;
1261   }
1262   else
1263   {
1264     GNUNET_assert (0 != (sock->ccs & COCO_RECEIVE_AGAIN));
1265     sock->ccs -= COCO_RECEIVE_AGAIN;
1266   }
1267   sock->receiver = NULL;
1268   return sock->receiver_cls;
1269 }
1270
1271
1272 /**
1273  * Try to call the transmit notify method (check if we do
1274  * have enough space available first)!
1275  *
1276  * @param sock socket for which we should do this processing
1277  * @return GNUNET_YES if we were able to call notify
1278  */
1279 static int
1280 process_notify (struct GNUNET_CONNECTION_Handle *sock)
1281 {
1282   size_t used;
1283   size_t avail;
1284   size_t size;
1285   GNUNET_CONNECTION_TransmitReadyNotify notify;
1286
1287   GNUNET_assert (sock->write_task == GNUNET_SCHEDULER_NO_TASK);
1288   if (NULL == (notify = sock->nth.notify_ready))
1289     return GNUNET_NO;
1290   used = sock->write_buffer_off - sock->write_buffer_pos;
1291   avail = sock->write_buffer_size - used;
1292   size = sock->nth.notify_size;
1293   if (size > avail)
1294     return GNUNET_NO;
1295   sock->nth.notify_ready = NULL;
1296   if (sock->write_buffer_size - sock->write_buffer_off < size)
1297   {
1298     /* need to compact */
1299     memmove (sock->write_buffer, &sock->write_buffer[sock->write_buffer_pos],
1300              used);
1301     sock->write_buffer_off -= sock->write_buffer_pos;
1302     sock->write_buffer_pos = 0;
1303   }
1304   avail = sock->write_buffer_size - sock->write_buffer_off;
1305   GNUNET_assert (avail >= size);
1306   size =
1307       notify (sock->nth.notify_ready_cls, avail,
1308               &sock->write_buffer[sock->write_buffer_off]);
1309   GNUNET_assert (size <= avail);
1310   sock->write_buffer_off += size;
1311   return GNUNET_YES;
1312 }
1313
1314
1315 /**
1316  * Task invoked by the scheduler when a call to transmit
1317  * is timing out (we never got enough buffer space to call
1318  * the callback function before the specified timeout
1319  * expired).
1320  *
1321  * This task notifies the client about the timeout.
1322  *
1323  * @param cls the 'struct GNUNET_CONNECTION_Handle'
1324  * @param tc scheduler context
1325  */
1326 static void
1327 transmit_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1328 {
1329   struct GNUNET_CONNECTION_Handle *sock = cls;
1330   GNUNET_CONNECTION_TransmitReadyNotify notify;
1331
1332   sock->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
1333   LOG (GNUNET_ERROR_TYPE_DEBUG,
1334        "Transmit to `%s:%u/%s' fails, time out reached (%p).\n",
1335        sock->hostname,
1336        sock->port, GNUNET_a2s (sock->addr, sock->addrlen), sock);
1337   GNUNET_assert (0 != (sock->ccs & COCO_TRANSMIT_READY));
1338   sock->ccs -= COCO_TRANSMIT_READY;     /* remove request */
1339   notify = sock->nth.notify_ready;
1340   sock->nth.notify_ready = NULL;
1341   notify (sock->nth.notify_ready_cls, 0, NULL);
1342 }
1343
1344
1345 /**
1346  * Task invoked by the scheduler when we failed to connect
1347  * at the time of being asked to transmit.
1348  *
1349  * This task notifies the client about the error.
1350  *
1351  * @param cls the 'struct GNUNET_CONNECTION_Handle'
1352  * @param tc scheduler context
1353  */
1354 static void
1355 connect_error (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1356 {
1357   struct GNUNET_CONNECTION_Handle *sock = cls;
1358   GNUNET_CONNECTION_TransmitReadyNotify notify;
1359
1360   LOG (GNUNET_ERROR_TYPE_DEBUG,
1361        "Transmission request of size %u fails (%s/%u), connection failed (%p).\n",
1362        sock->nth.notify_size, sock->hostname, sock->port, sock);
1363   sock->write_task = GNUNET_SCHEDULER_NO_TASK;
1364   notify = sock->nth.notify_ready;
1365   sock->nth.notify_ready = NULL;
1366   notify (sock->nth.notify_ready_cls, 0, NULL);
1367 }
1368
1369
1370 /**
1371  * FIXME
1372  *
1373  * @param sock FIXME
1374  */
1375 static void
1376 transmit_error (struct GNUNET_CONNECTION_Handle *sock)
1377 {
1378   GNUNET_CONNECTION_TransmitReadyNotify notify;
1379
1380   if (NULL != sock->sock)
1381   {
1382     GNUNET_NETWORK_socket_shutdown (sock->sock, SHUT_RDWR);
1383     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock->sock));
1384     sock->sock = NULL;
1385     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == sock->write_task);
1386   }
1387   if (sock->read_task != GNUNET_SCHEDULER_NO_TASK)
1388   {
1389     GNUNET_SCHEDULER_cancel (sock->read_task);
1390     sock->read_task = GNUNET_SCHEDULER_NO_TASK;
1391     signal_timeout (sock);
1392     return;
1393   }
1394   if (sock->nth.notify_ready == NULL)
1395     return;                     /* nobody to tell about it */
1396   notify = sock->nth.notify_ready;
1397   sock->nth.notify_ready = NULL;
1398   notify (sock->nth.notify_ready_cls, 0, NULL);
1399 }
1400
1401
1402 /**
1403  * See if we are now connected.  If not, wait longer for
1404  * connect to succeed.  If connected, we should be able
1405  * to write now as well, unless we timed out.
1406  *
1407  * @param cls our connection handle
1408  * @param tc task context describing why we are here
1409  */
1410 static void
1411 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1412 {
1413   struct GNUNET_CONNECTION_Handle *sock = cls;
1414   GNUNET_CONNECTION_TransmitReadyNotify notify;
1415   ssize_t ret;
1416   size_t have;
1417
1418   LOG (GNUNET_ERROR_TYPE_DEBUG, "transmit_ready running (%p).\n", sock);
1419   GNUNET_assert (sock->write_task != GNUNET_SCHEDULER_NO_TASK);
1420   sock->write_task = GNUNET_SCHEDULER_NO_TASK;
1421   GNUNET_assert (sock->nth.timeout_task == GNUNET_SCHEDULER_NO_TASK);
1422   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1423   {
1424     if ((sock->ignore_shutdown == GNUNET_YES) && (NULL != sock->sock))
1425       goto SCHEDULE_WRITE;      /* ignore shutdown, go again immediately */
1426     LOG (GNUNET_ERROR_TYPE_DEBUG,
1427          "Transmit to `%s' fails, shutdown happened (%p).\n",
1428          GNUNET_a2s (sock->addr, sock->addrlen), sock);
1429     notify = sock->nth.notify_ready;
1430     if (NULL != notify)
1431     {
1432       sock->nth.notify_ready = NULL;
1433       notify (sock->nth.notify_ready_cls, 0, NULL);
1434     }
1435     return;
1436   }
1437   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1438   {
1439     LOG (GNUNET_ERROR_TYPE_DEBUG,
1440          "Transmit to `%s' fails, time out reached (%p).\n",
1441          GNUNET_a2s (sock->addr, sock->addrlen), sock);
1442     notify = sock->nth.notify_ready;
1443     GNUNET_assert (NULL != notify);
1444     sock->nth.notify_ready = NULL;
1445     notify (sock->nth.notify_ready_cls, 0, NULL);
1446     return;
1447   }
1448   GNUNET_assert (NULL != sock->sock);
1449   if (tc->write_ready == NULL)
1450   {
1451     /* special circumstances (in particular,
1452      * PREREQ_DONE after connect): not yet ready to write,
1453      * but no "fatal" error either.  Hence retry.  */
1454     goto SCHEDULE_WRITE;
1455   }
1456   if (!GNUNET_NETWORK_fdset_isset (tc->write_ready, sock->sock))
1457   {
1458     LOG (GNUNET_ERROR_TYPE_INFO,
1459          _
1460          ("Could not satisfy pending transmission request, socket closed or connect failed (%p).\n"),
1461          sock);
1462     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == sock->write_task);
1463     transmit_error (sock);
1464     return;                     /* connect failed for good, we're finished */
1465   }
1466   GNUNET_assert (sock->write_buffer_off >= sock->write_buffer_pos);
1467   if ((sock->nth.notify_ready != NULL) &&
1468       (sock->write_buffer_size < sock->nth.notify_size))
1469   {
1470     sock->write_buffer =
1471         GNUNET_realloc (sock->write_buffer, sock->nth.notify_size);
1472     sock->write_buffer_size = sock->nth.notify_size;
1473   }
1474   process_notify (sock);
1475   have = sock->write_buffer_off - sock->write_buffer_pos;
1476   if (have == 0)
1477   {
1478     /* no data ready for writing, terminate write loop */
1479     return;
1480   }
1481   GNUNET_assert (have <= sock->write_buffer_size);
1482   GNUNET_assert (have + sock->write_buffer_pos <= sock->write_buffer_size);
1483   GNUNET_assert (sock->write_buffer_pos <= sock->write_buffer_size);
1484 RETRY:
1485   ret =
1486       GNUNET_NETWORK_socket_send (sock->sock,
1487                                   &sock->write_buffer[sock->write_buffer_pos],
1488                                   have);
1489   if (ret == -1)
1490   {
1491     if (errno == EINTR)
1492       goto RETRY;
1493     LOG_STRERROR (GNUNET_ERROR_TYPE_DEBUG, "send");
1494     if (GNUNET_SCHEDULER_NO_TASK != sock->write_task)
1495     {
1496       GNUNET_SCHEDULER_cancel (sock->write_task);
1497       sock->write_task = GNUNET_SCHEDULER_NO_TASK;
1498     }
1499     transmit_error (sock);
1500     return;
1501   }
1502   LOG (GNUNET_ERROR_TYPE_DEBUG,
1503        "transmit_ready transmitted %u/%u bytes to `%s' (%p)\n",
1504        (unsigned int) ret, have, GNUNET_a2s (sock->addr, sock->addrlen), sock);
1505   sock->write_buffer_pos += ret;
1506   if (sock->write_buffer_pos == sock->write_buffer_off)
1507   {
1508     /* transmitted all pending data */
1509     sock->write_buffer_pos = 0;
1510     sock->write_buffer_off = 0;
1511   }
1512   if ((sock->write_buffer_off == 0) && (NULL == sock->nth.notify_ready))
1513     return;                     /* all data sent! */
1514   /* not done writing, schedule more */
1515 SCHEDULE_WRITE:
1516   LOG (GNUNET_ERROR_TYPE_DEBUG,
1517        "Re-scheduling transmit_ready (more to do) (%p).\n", sock);
1518   have = sock->write_buffer_off - sock->write_buffer_pos;
1519   GNUNET_assert ((sock->nth.notify_ready != NULL) || (have > 0));
1520   if (sock->write_task == GNUNET_SCHEDULER_NO_TASK)
1521     sock->write_task =
1522         GNUNET_SCHEDULER_add_write_net ((sock->nth.notify_ready ==
1523                                          NULL) ? GNUNET_TIME_UNIT_FOREVER_REL :
1524                                         GNUNET_TIME_absolute_get_remaining
1525                                         (sock->nth.transmit_timeout),
1526                                         sock->sock, &transmit_ready, sock);
1527 }
1528
1529
1530 /**
1531  * Ask the socket to call us once the specified number of bytes
1532  * are free in the transmission buffer.  May call the notify
1533  * method immediately if enough space is available.
1534  *
1535  * @param sock socket
1536  * @param size number of bytes to send
1537  * @param timeout after how long should we give up (and call
1538  *        notify with buf NULL and size 0)?
1539  * @param notify function to call
1540  * @param notify_cls closure for notify
1541  * @return non-NULL if the notify callback was queued,
1542  *         NULL if we are already going to notify someone else (busy)
1543  */
1544 struct GNUNET_CONNECTION_TransmitHandle *
1545 GNUNET_CONNECTION_notify_transmit_ready (struct GNUNET_CONNECTION_Handle *sock,
1546                                          size_t size,
1547                                          struct GNUNET_TIME_Relative timeout,
1548                                          GNUNET_CONNECTION_TransmitReadyNotify
1549                                          notify, void *notify_cls)
1550 {
1551   if (sock->nth.notify_ready != NULL)
1552   {
1553     GNUNET_assert (0);
1554     return NULL;
1555   }
1556   GNUNET_assert (notify != NULL);
1557   GNUNET_assert (size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1558   GNUNET_assert (sock->write_buffer_off <= sock->write_buffer_size);
1559   GNUNET_assert (sock->write_buffer_pos <= sock->write_buffer_size);
1560   GNUNET_assert (sock->write_buffer_pos <= sock->write_buffer_off);
1561   sock->nth.notify_ready = notify;
1562   sock->nth.notify_ready_cls = notify_cls;
1563   sock->nth.sh = sock;
1564   sock->nth.notify_size = size;
1565   sock->nth.transmit_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1566   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == sock->nth.timeout_task);
1567   if ((sock->sock == NULL) && (sock->ap_head == NULL) &&
1568       (sock->dns_active == NULL))
1569   {
1570     if (sock->write_task != GNUNET_SCHEDULER_NO_TASK)
1571       GNUNET_SCHEDULER_cancel (sock->write_task);
1572     sock->write_task = GNUNET_SCHEDULER_add_now (&connect_error, sock);
1573     return &sock->nth;
1574   }
1575   if (GNUNET_SCHEDULER_NO_TASK != sock->write_task)
1576     return &sock->nth;
1577   if (sock->sock != NULL)
1578   {
1579     LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduling transmit_ready (%p).\n", sock);
1580     sock->write_task =
1581         GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
1582                                         (sock->nth.transmit_timeout),
1583                                         sock->sock, &transmit_ready, sock);
1584   }
1585   else
1586   {
1587     LOG (GNUNET_ERROR_TYPE_DEBUG,
1588          "CCS-Scheduling transmit_ready, adding timeout task (%p).\n", sock);
1589     sock->ccs |= COCO_TRANSMIT_READY;
1590     sock->nth.timeout_task =
1591         GNUNET_SCHEDULER_add_delayed (timeout, &transmit_timeout, sock);
1592   }
1593   return &sock->nth;
1594 }
1595
1596
1597 /**
1598  * Cancel the specified transmission-ready notification.
1599  *
1600  * @param th notification to cancel
1601  */
1602 void
1603 GNUNET_CONNECTION_notify_transmit_ready_cancel (struct
1604                                                 GNUNET_CONNECTION_TransmitHandle
1605                                                 *th)
1606 {
1607   GNUNET_assert (th->notify_ready != NULL);
1608   if (0 != (th->sh->ccs & COCO_TRANSMIT_READY))
1609   {
1610     LOG (GNUNET_ERROR_TYPE_DEBUG,
1611          "notify_transmit_ready_cancel cancels timeout_task (%p)\n", th);
1612     GNUNET_SCHEDULER_cancel (th->timeout_task);
1613     th->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1614     th->sh->ccs -= COCO_TRANSMIT_READY;
1615   }
1616   else
1617   {
1618     if (th->sh->write_task != GNUNET_SCHEDULER_NO_TASK)
1619     {
1620       GNUNET_SCHEDULER_cancel (th->sh->write_task);
1621       th->sh->write_task = GNUNET_SCHEDULER_NO_TASK;
1622     }
1623   }
1624   th->notify_ready = NULL;
1625 }
1626
1627 /* end of connection.c */