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