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