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