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