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