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