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