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