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